如何在指令中设置插值?我可以从以下代码中读取正确的值,但无法设置它。
js:
app.directive('ngMyDirective', function () {
return function(scope, element, attrs) {
console.log(scope.$eval(attrs.ngMyDirective));
//set the interpolated attrs.ngMyDirective value somehow!!!
}
});
html:
<div ng-my-directive="myscopevalue"></div>
其中 myscopevalue
是我的 Controller 范围内的值。
最佳答案
只要指令不使用隔离范围,并且您使用属性指定范围属性,并且您想要更改该属性的值,我建议使用 $parse 。 (我认为语法比 $eval 更好。)
app.directive('ngMyDirective', function ($parse) {
return function(scope, element, attrs) {
var model = $parse(attrs.ngMyDirective);
console.log(model(scope));
model.assign(scope,'Anton');
console.log(model(scope));
}
});
$parse
无论属性是否包含点都有效。
关于angularjs - 如何在 Angular 指令中设置插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494457/