0

I am trying to create a directive with data who comes from ajax call, my problem is the data is undefined when the directive is created because ajax is still loading, I know with a setTimeout to validate this and use $scope.apply() it could be works, but it doesn't seems a good approach and also try to add $watch to flag ajaxLoading but it doesn't works.

pmApp.directive("filter", function () {
    return {
        restrict: "A",
        scope: {
            data: '=',
            ngModel: '=',
            display: '='
        },
        templateUrl: "views/template.html",
        link: function (scope, element, attrs) {
            var value = attrs.value,
                scopeParent = scope.$parent,
                model = attrs.ngModel;

            scope.description = attrs.description;
            scope.value = value;

            window.setTimeout(function() {
                scope.ngModel = scope.data[0][value];
                scope.$apply();
            }, 2000);


        }
    }
});
4
  • where is your ajax call?
    – peaceman
    Nov 29, 2013 at 12:45
  • Add a watch on the data object that is filled by the ajax call. Since you are using isolated scopes you need to pass the data object that is filled using ajax. Nov 29, 2013 at 13:03
  • @Chandermani How can I the pass the data object?
    – mrojas
    Nov 29, 2013 at 13:12
  • You are already passing it in data variable. See if a watch on data works inside directive. What is the structure of your data object? Nov 29, 2013 at 15:08

1 Answer 1

0

Whatever method you use for that ajax call, it should return a promise. Save this promise on your controller and pass it in the directives scope configuration, so that the directive can access it.

Now you can use the promise, to delay your variable assignment, instead of setTimeout.

But as a general recommendation, you should use the builtin $timeout Service instead of setTimeout, so you don't have to worry about digest cycles. For detailed information visit https://coderwall.com/p/udpmtq.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.