我可以组合隔离范围和继承范围吗?

时间:2014-10-13 11:45:28

标签: javascript angularjs angularjs-directive angularjs-scope

是否可以组合隔离范围和继承范围?

我有以下结构:

<my-parent-directive>
    <my-directive ng-repeat="foo in foos" foo="foo"></my-directive>
</my-parent-directive>


app.module("app").directive("myParentDirective", function(){
   return {
       //other directive properties
       controller: function($scope) {
                      $scope.myFunc(){//function I want to call from child element
                        //dostuff
                      };
       },
       link: function($scope){
            $scope.foos = ["foo", "bar"];
       }
   };
});

app.module("app").directive("myDirective", function(){
    return {
       //other directive properties
       scope : {foo: "="},
       template: "<button ng-click='doStuff()'>doStuff</button>",
       controller: function($scope){ //need controller here to do other stuff as well},
       link: function($scope){
            $scope.doStuff = function() {
               //do stuff plus call myFunc
               $scope.myFunc();//declared in "parent scope". This does not work
            }
       }
    };
});

所以是的。有没有办法做到这一点?

我使用隔离范围获得&#34; foo&#34;来自父范围的ng-repeat&#34; foos&#34; -array。

之前我从子元素中发出了一个事件,并在&#34; parent&#34;上进行了监听,但我宁愿使用范围来做。有办法还是我需要使用活动?

1 个答案:

答案 0 :(得分:1)

当然可以!你的内部指令具有孤立的范围,所以看不到任何外部的东西,但你可以使用'&amp;'将函数传递给你的指令。绑定,因此您的指令可能类似于:

<my-directive foo="func()"></my-directive>

我给你做了一个小提琴here

相关问题