我是angularJs的新手,currently working example(fiddle)感觉不对劲。当你试图模糊字段时,它应该递增event.times
,目前我在第10行的$apply
上做,所以我想问有没有更好的方法来实现这一目标?可能是这样的var times = scope.$get(attrs.timesField);
然后是scope.$apply(function(){ times += 1; });
答案 0 :(得分:3)
每当指令不使用隔离范围并使用属性指定范围属性,并且您想要更改该属性的值时,请使用$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();
});
}
答案 1 :(得分:0)
你是对的,这不是做这样的事情的正确方法。 找出$watch()函数,尤其是在directives中使用它时。
答案 2 :(得分:0)
这里没有必要使用eval,你可以这样做:
scope.$apply(function(){
scope.event.times++;
});
但是,在使用此指令之前,您必须确保作用域上存在事件对象,并且我认为指令不依赖于在其他位置设置的数据。
你到底想要实现什么目标?