我是angularJs的新手,目前的工作示例(fiddle)感觉不太好。当你试图模糊字段,它应该增加event.times
,目前我做$apply
在第10行,所以我问有没有更好的方法来实现这一点?比如var times = scope.$get(attrs.timesField);
和scope.$apply(function(){ times += 1; });
当一个指令没有使用隔离作用域,而你用一个属性指定了一个作用域属性,并且你想要改变这个属性的值时,使用$parse:
<input custom-field times-field="event.times" ng-model="event.title" type="text">
link: function (scope, element, attrs){
var model = $parse(attrs.timesField);
element.bind('blur', function(){
model.assign(scope, model(scope) + 1);
scope.$apply();
});
}
小提琴
你说得对,这不是正确的做法。找出$watch()函数,特别是在指令中使用它时。
这里不需要使用eval,您可以这样做:
scope.$apply(function(){
scope.event.times++;
});
然而,你必须确保在使用这个指令之前,一个事件对象存在于作用域中,我不认为指令依赖于其他地方设置的数据是好的。
你到底想达到什么目标?