【问题标题】:How to access elements attributes from custom directive while keeping access to parent scope?如何从自定义指令访问元素属性,同时保持对父范围的访问?
【发布时间】:2014-10-05 02:17:04
【问题描述】:

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

例如相关的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>

directive.html

{{testAttribute}}
{{name}}

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

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

【问题讨论】:

  • 在你的directive.html中,你可以使用{{$parent.name}}来访问属性name。但这是不合适的,因为它不会促进可重用性。

标签: javascript angularjs angular-directive


【解决方案1】:

对于您要执行的操作,不需要双向绑定。您正在尝试访问分配为属性的文本。你可以把你的指令写成:-

.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 way binding。但在这一点上,由于不确定您最初的目标是什么,因此这是一个基于您的问题的解决方案。

总结一下:-

我希望能够访问我创建的指令的父范围

移除隔离作用域,只使用父作用域。

但我也希望能够访问我放置在元素上的属性。

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

【讨论】:

  • 嘿,感谢您的详尽解释,它运行良好,但是当您有多个指令时,它似乎采用最后一个指令的属性并将其应用于所有指令。 example
  • 像这样.. plnkr.co/edit/IGc3tK?p=preview.我回答的最后一行。您还可以使用 2 路绑定(如果需要)。
猜你喜欢
  • 2015-09-20
  • 1970-01-01
  • 2013-07-27
  • 2013-05-22
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多