Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive does not update on scope variable changes

I've tried to write a small directive, to wrap its contents with another template file.

This code:

<layout name="Default">My cool content</layout>

Should have this output:

<div class="layoutDefault">My cool content</div>

Because the layout "Default" has this code:

<div class="layoutDefault">{{content}}</div>

Here the code of the directive:

app.directive('layout', function($http, $compile){
return {
    restrict: 'E',
    link: function(scope, element, attributes) {
        var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
        $http.get(scope.constants.pathLayouts + layoutName + '.html')
            .success(function(layout){
                var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
                var result = regexp.exec(layout);

                var templateWithLayout = result[1] + element.html() + result[2];
                element.html($compile(templateWithLayout)(scope));
            });
    }
}

});

My problem:

When I'm using scope variables in template (in layout template or inside of layout tag), eg. {{whatever}} it just work initially. If I update the whatever variable, the directive is not updated anymore. The whole link function will just get triggered once.

I think, that AngularJS does not know, that this directive uses scope variables and therefore it will not be updated. But I have no clue how to fix this behavior.

like image 989
Armin Avatar asked Nov 19 '13 10:11

Armin


4 Answers

You should create a bound scope variable and watch its changes:

return {
   restrict: 'E',
   scope: {
     name: '='
   },
   link: function(scope) {
     scope.$watch('name', function() {
        // all the code here...
     });
   }
};
like image 188
QuarK Avatar answered Oct 19 '22 02:10

QuarK


I needed a solution for this issue as well and I used the answers in this thread to come up with the following:

.directive('tpReport', ['$parse', '$http', '$compile', '$templateCache', function($parse, $http, $compile, $templateCache)
    {
        var getTemplateUrl = function(type)
        {
            var templateUrl = '';

            switch (type)
            {
                case 1: // Table
                    templateUrl = 'modules/tpReport/directives/table-report.tpl.html';
                    break;
                case 0:
                    templateUrl = 'modules/tpReport/directives/default.tpl.html';
                    break;
                default:
                    templateUrl = '';
                    console.log("Type not defined for tpReport");
                    break;
            }

            return templateUrl;
        };

        var linker = function (scope, element, attrs)
        {

            scope.$watch('data', function(){
                var templateUrl = getTemplateUrl(scope.data[0].typeID);
                var data = $templateCache.get(templateUrl);
                element.html(data);
                $compile(element.contents())(scope);

            });



        };

        return {
            controller: 'tpReportCtrl',
            template: '<div>{{data}}</div>',
            // Remove all existing content of the directive.
            transclude: true,
            restrict: "E",
            scope: {
                data: '='
            },
            link: linker
        };
    }])
    ;

Include in your html:

<tp-report data='data'></tp-report>

This directive is used for dynamically loading report templates based on the dataset retrieved from the server.

It sets a watch on the scope.data property and whenever this gets updated (when the users requests a new dataset from the server) it loads the corresponding directive to show the data.

like image 35
Roy Milder Avatar answered Oct 19 '22 04:10

Roy Milder


You need to tell Angular that your directive uses a scope variable:

You need to bind some property of the scope to your directive:

return {
    restrict: 'E',
    scope: {
      whatever: '='
    },
   ...
}

and then $watch it:

  $scope.$watch('whatever', function(value) {
    // do something with the new value
  });

Refer to the Angular documentation on directives for more information.

like image 17
Paul Mougel Avatar answered Oct 19 '22 04:10

Paul Mougel


I've found a much better solution:

app.directive('layout', function(){
    var settings = {
        restrict: 'E',
        transclude: true,
        templateUrl: function(element, attributes){
            var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
            return constants.pathLayouts + layoutName + '.html';
        }
    }
    return settings;
});

The only disadvantage I see currently, is the fact that transcluded templates got their own scope. They get the values from their parents, but instead of change the value in the parent, the value get stored in an own, new child-scope. To avoid this, I am now using $parent.whatever instead of whatever.

Example:

<layout name="Default">
    <layout name="AnotherNestedLayout">
        <label>Whatever:</label>
        <input type="text" ng-model="$parent.whatever">
    </layout>
</layout>
like image 8
Armin Avatar answered Oct 19 '22 03:10

Armin