当属性更改时,AngularJS绑定不起作用

时间:2014-04-03 08:48:40

标签: javascript angularjs angularjs-directive

我创建了一个指令,它有一个隔离范围:

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

当我尝试按"text"方法更改.attr属性时,绑定不起作用。我尝试使用$apply方法,但没有任何成功。

有什么问题?

JSFiddle

PS:请不要建议使用控制器并将text属性绑定到$scope的属性(类似于<title text="{{somepropertyincontrollersscope}}">...)的任何解决方案。我的问题是与更改属性外部相关。

1 个答案:

答案 0 :(得分:1)

我认为您必须通过观察属性的值在link函数中执行此操作:

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

这是一个updated fiddle