angularjsangularjs-directiveangularjs-watchcontrolleras

How to use an isolated scope property properly?


How to use an isolated scope property properly?

I have a directive, that is called from a page controller, with an attribute item passed to it, e.g. <my-directive item="myItem"></my-directive>, containing an id.

The code below will not work, as it seems like $scope.item is undefined in the controller.. like I'm using it too soon. How can I be sure that it is actually set when I want to use it?

app.directive('myDirective', [function() {
return {
    restrict: 'E',
    templateUrl: 'template.html',
    scope: {
        item: "="
    },
    controller: ['$scope', 'ExtendedItemFactory', function($scope, ExtendedItemFactory) {
        this.extendedInfo = ExtendedItemFactory.get({ id: $scope.item.id });
    }],
    controllerAs: 'MyDirectiveCtrl'
};
}]);

Solution

  • You could use $watch inside your directive that will watch on change in value & will fire the code which you want.

    Code

    app.directive('myDirective', [function() {
        return {
            restrict: 'E',
            templateUrl: 'template.html',
            scope: {
                item: "="
            },
            controller: ['$scope', 'ExtendedItemFactory', function($scope, ExtendedItemFactory) {
                this.extendedInfo = ExtendedItemFactory.get({
                    id: $scope.item.id
                });
                $scope.$watch('item', function(newVal, oldVal) {
                    if (newVal && newVal != oldVal)
                        this.extendedInfo = ExtendedItemFactory.get({
                            id: $scope.item.id
                        });
                }, true).bind(this);
            }],
            controllerAs: 'MyDirectiveCtrl'
        };
    }]);