Question

I'm setting up a directive like so (timeout function just as a demo):

app.directive('timeRange', function () {
    return {
        restrict: 'A',
        scope: {
            sliderId: "@sliderId",
        },
        template:   '<div id="{{sliderId}}"></div>'+
                    '<p>From: <span>{{fromVal}}</span>'+
                        '<span style="float:right;">{{toVal}}</span><span style="float:right;">To: </span>'+
                    '</p>',
        link: function (scope, elem, attrs) {

            scope.sliderId = 'NewId';
            scope.fromVal = '06:00';
            scope.toVal = '17:00';

            setTimeout(function(){
                scope.fromVal = 'Hello';
                log("Changed");
            }, 2000);
        },
    };
});

When the timeout function runs, the HTML doesn't update, the value stays at 06:00. How do I get the template to update when the variable does? Do I need to somehow link it in the scope section where I link the attribute?

Was it helpful?

Solution

The only issue I can see with your example is that you are using setTimeout instead of the $timeout service. Any time you change angular or scope variables this way you are going to have to manually call $scope.$apply() which is what the $timeout service does for you. The following code works better then:

app.directive('timeRange', function ($timeout) {
    return {
        restrict: 'A',
        scope: {
            sliderId: "@sliderId",
        },
        template:   '<div id="{{sliderId}}"></div>'+
                    '<p>From: <span>{{fromVal}}</span>'+
                        '<span style="float:right;">{{toVal}}</span><span style="float:right;">To: </span>'+
                    '</p>',
        link: function (scope, elem, attrs) {

            scope.sliderId = 'NewId';
            scope.fromVal = '08:00';
            scope.toVal = '17:00';

            $timeout(function(){
                scope.fromVal = 'Hello';
                console.log("Changed");
            }, 2000);
        },
    };
});

Note the injection of $timeout and the way it is used.

See This In Plunker: http://plnkr.co/edit/KlRAeg6cVhehw2EhWzCK?p=preview

Fixing The Original...

The fixed original code looks like (just a snippet):

setTimeout(function(){
    scope.fromVal = 'Hello';
    scope.$apply();
    console.log("Changed");
}, 2000);

Best of luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top