Engineer
Engineer

Reputation: 48793

AngularJS binding does not work,when attribute is changed

I have created a directive, which has an isolated-scope:

.directive('title',function(){
    return {
        restrict:'E',
        scope:{
            text:'@'
        },
        replace:true,
        template:'<div>{{text}}</div>',
        link:function(scope,iElement,iAttrs){
        }
    };
})

When I am trying to change "text" attribute by .attr method, the binding does not work. I have tried to use $apply method, but without any success.

What is wrong?

JSFiddle

PS: Pls, do not suggest any solution with using controller and binding the text attribute to $scope's properties(something like a <title text="{{somepropertyincontrollersscope}}">...). My problem is only related to changing the attribute externally.

Upvotes: 1

Views: 52

Answers (1)

James Allardice
James Allardice

Reputation: 165971

I think you'll have to do it in the link function by watching the value of the attribute:

scope.$watch(function () {
    return iElement.attr("text");
}, function (newVal) {
    scope.text = newVal;
});

Here's an updated fiddle.

Upvotes: 1

Related Questions