angularjs - 如何在 Angular 指令中设置插值?

标签 angularjs angularjs-directive angularjs-scope

如何在指令中设置插值?我可以从以下代码中读取正确的值,但无法设置它。

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));
    }
});

fiddle

$parse 无论属性是否包含点都有效。

关于angularjs - 如何在 Angular 指令中设置插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16494457/

相关文章:

javascript - 将 angularjs $http 响应转换为 string/JSON

angularjs - 为什么$ stateChangeStart会多次触发?

javascript - 在模板中附加 ng-click 不会破坏 MV* 的目的吗?

javascript - 从 div 到 div 的 Angular 移动指令

angularjs - 为什么我无法获取自定义指令的属性值?

javascript - Angular 疯狂 bool 派对

html - 超出组件范围的 Angular2+ 样式父级

javascript - 如何在选择字段中赋予值?

javascript - Angular.js 对 ng-repeat 的一项进行更改,导致所有其他项上的过滤器运行

javascript - 访问 View 中的 AngularJS 变量?