如何从儿童范围指令设置角度控制器对象的属性值 [英] How to set angular controller object property value from directive in child scope
问题描述
我有一个应该设定一个范围属性的NG-中继器内部的指令。
请在这里看到小提琴: http://jsfiddle.net/paos/CSbRB/
I have have a directive inside an ng-repeater that should set a scope property. Please see the fiddle here: http://jsfiddle.net/paos/CSbRB/
的问题是,该范围属性被给定为这样一个属性值:
The problem is that the scope property is given as an attribute value like this:
<button ng-update1="inputdata.title">click me</button>
该指令应该设置scope属性inputdata.title一些字符串。这不工作:
The directive is supposed to set the scope property inputdata.title to some string. This does not work:
app.directive('ngUpdate1', function() {
return function(scope, element, attrs) {
element.bind('click', function() {
scope.$apply(function() {
scope[ attrs.ngUpdate1 ] = "Button 1";
});
});
};
});
但是,直接分配如下:
However, assigning directly works:
scope["inputdata"]["title"] = "Button 1";
你能告诉我怎样才能设置一个scope属性。在其名称中的符号从指令?
Can you please tell me how I can set a scope property with . notation in its name from a directive?
PS:小提琴是使用中继器的原因是因为它使指令在子作用域。当他们在一个孩子的范围,你不能写是原语作用域属性。这就是为什么我需要一个对象的属性。在名字里。看到这里长解释:<一href=\"http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482\">What范围是原型/原型继承的细微差别AngularJS?
PS: The reason the fiddle is using a repeater is because it makes the directives be in child scopes. When they are in a child scope, you can't write to scope properties that are primitives. That's why I need an object property with "." in the name. See the long explanation here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
感谢您
推荐答案
$解析将解决你的问题
<button ng-update1="inputdata.title">
app.directive('ngUpdate1', function($parse) {
return function(scope, element, attrs) {
var model = $parse(attrs.ngUpdate1);
console.log(model(scope)); // logs "test"
element.bind('click', function() {
model.assign(scope, "Button 1");
scope.$apply();
});
};
});
每当指令不使用分离的范围和指定使用属性的作用域属性,你要修改的值,可以使用 $解析
。
Whenever a directive does not use an isolate scope and you specify a scope property using an attribute, and you want to modify the value, use $parse
.
如果您不需要修改这个值,可以使用 $ EVAL
而不是:
If you don't need to modify the value, you can use $eval
instead:
console.log(scope.$eval(attrs.ngUpdate1));
这篇关于如何从儿童范围指令设置角度控制器对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!