如何在指令中修改范围的值 [英] How to modify a scope's value within a directive
问题描述
在一个指令,我想单击一个按钮时,修改前pression的价值。下面code仅修改值我的本地指令中。我想改变这个指令之外的价值。我怎样才能做到呢?
Within a directive, I'd like to modify the expression's value when a button is clicked. The below code is only modifying the value locally within my directive. I'd like to change the value outside of this directive as well. How can I accomplish that?
scope: false,
link: function (scope, el, attrs) {
//toggle the state when clicked
el.bind('click', function () {
scope[attrs.ngModel] = !scope[attrs.ngModel];
});
Plunker: http://plnkr.co/edit/xqYBnz5BHLP844kXJXKs?p=preVIEW
推荐答案
的问题是,在NG-模型结合前pression。因为它具有'。在这里面,你需要使用 $解析
来得到正确的设定值。看到一些文档这里
The problems is with the binding expression in ng-model. Since it has '.' in it, you need to use the $parse
to get and set value correctly. See some documentation here
像
var getter=$parse(attrs.ngModel);
var setter=getter.assign;
setter(scope,!getter(scope));
请参阅我的更新plunkr这里 http://plnkr.co/edit/VAE43y5cagCF8jq5AlaY? p = preVIEW
See my updated plunkr here http://plnkr.co/edit/VAE43y5cagCF8jq5AlaY?p=preview
基本上设置
scope[attrs.ngModel] = !scope[attrs.ngModel]
创建了一个新的属性 user.active
。要设置它应该是范围['用户'] ['主动'];
这篇关于如何在指令中修改范围的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!