0

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

例如相关的js

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

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

索引.html

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

指令.html

{{testAttribute}}
{{name}}

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

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

4

1 回答 1

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

演示

现在,指令设置的范围属性将使用父范围本身。但是您可能想要使用的理想场景scope:true(父级的子范围)或2 way binding机智的隔离范围。但是在这一点上,由于不确定您最初的目标是什么,因此这是一个基于您的问题的解决方案。

所以总结一下: -

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

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

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

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

于 2014-10-05T02:42:15.903 回答