javascript - 如何从自定义指令访问元素属性,同时保持对父范围的访问?

标签 javascript angularjs angular-directive

本质上,我希望能够访问我创建的指令的父范围,但我也希望能够访问我放置在元素上的属性。

例如相关js

app.directive('testDirective', function(){
    return {
        restrict:"E",
        templateUrl:"directive.html",
        scope:{
            testAttribute: '='
        }
    };
});

app.controller('mainCtrl', function($scope){
     $scope.name = 'henry'
}

index.html

<div ng-controller="mainCtrl">
    <test-directive test-attribute="Hello"></test-directive>
</div>

指令.html

{{testAttribute}}
{{name}}

输出是“Hello”而不是“Hello Henry”

所以澄清一下,我想要做的就是访问属性和父范围。

最佳答案

对于您想要做的事情,不需要双向绑定(bind)。您正在尝试访问指定为属性的文本。您可以将指令写为:-

.directive('testDirective', function(){
    return {
        restrict:"E",
        //scope:true,   //apply if required
        templateUrl:"directive.html",
        link:function(scope, elm, attrs){
           scope.testAttribute = attrs.testAttribute; //Get it from attributes
        }
    };
});

<强> Demo

现在指令设置的作用域属性将使用父作用域本身。但理想的情况下,您可能希望使用 scope:true (父级的子级范围)或具有隔离范围的 2 路绑定(bind)。但此时,由于不太确定您最初的目标是什么,这是一个基于您的问题的解决方案。

总结一下:-

I want to be able to access the parent scope of the directive I have created

删除隔离范围并仅使用父级范围。

but I also want to be able to access the attributes that I have placed onto the element.

使用链接函数的attrs参数(attrs.testAttribute)。如果您想将其评估为绑定(bind)值,请执行 (scope.$eval(attrs.testAttribute))

关于javascript - 如何从自定义指令访问元素属性,同时保持对父范围的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26199011/

相关文章:

javascript - 加载 Angular 库时 IE9 和 IE10 中的 Angular JS "SCRIPT5007: Object expected"错误

javascript - 如何使用来自 http 请求的数组将动态输入字段添加到 Angular 形式

javascript - 将模型数据嵌入到 Rails 4 中的 JavaScript 变量中时出错

javascript - 安装webpack分离依赖?

angularjs - 将数据从父级传递到子级 angular.js 组件

javascript - 如何删除 Angular ng-repeat中最后一个li的<hr/>

angular - 从指令中创建/获取 TemplateRef

Angular 指令从元素中删除原始属性

javascript - <table> 中每个 block 的 localstorage setitem

javascript - 如何使用Python/Flask在heroku中显示index.html页面