从指令内部访问主控制器的范围

时间:2017-01-19 16:08:46

标签: angularjs angularjs-directive angularjs-scope

假设以下蓝图代码:

<div ng-controller="myCtrl">
    <div ng-repeat="...">
        <div ng-repeat="...">
            <div ng-repeat="...">
                <div ng=if="..." my-directive>
                </div>
            </div>
        </div>
    </div>
</div>    

myApp.directive('myDirective',  function() {
    return {                   
        controller: function($scope){
            console.log('controller scope');
            console.log($scope);
        },  
        link:function(scope,element){ 
            console.log('link scope');
            console.log(scope);    
        }
    }
});

控制台中的两个输出都将指向ng-if指令创建的范围。我的问题是如何从指令中访问myCtrl的范围。当然不是通过使用$ parent。$ parent ....

3 个答案:

答案 0 :(得分:1)

最简单的方法是在指令中使用require,例如:

<div ng-controller="MyCtrl">
   <div my-directive></div>
</div>


var myApp = angular.module("app", []);

myApp.controller("MyCtrl", function($scope) {
    this.text = "I am in Controller Scope";
    this.getValue = function() { return this.text; };
});

myApp.directive("myDirective", function() {
    return {
        require: "^ngController",
        link: function(scope, elem, attrs, ngCtrl) {
            elem.text(ngCtrl.getValue());
        }
    };
});

修改

在您的情况下,我认为您可以使用范围绑定&来使用指令中的控制器范围变量和方法;下面的代码段:

<div ng-controller="MyCtrl as vm">
    <my-directive on-get-value="vm.getValue()">
    </my-directive>
 </div>

angular.module('app', [])
.controller('MyCtrl', function($window) {
    var vm = this;
    vm.getValue = function() { $window.alert("I am in Controller Scope"); };
})
.directive('myDirective', function() {
  return {
    scope: {
       onGetValue:'&'
    },
    controllerAs:'vm',
    controller: function($scope) {
         $scope.onGetValue();
    }
  };
});

答案 1 :(得分:0)

使用服务在角度组件之间共享数据。这个问题可能是一个好的开始:Share data between AngularJS controllers。这种方法也适用于在控制器和指令之间共享数据

答案 2 :(得分:0)

创建指令时,返回的函数称为DDO(指令定义对象)。其中一个属性是&#39;范围&#39;。如果使用scope:true初始化它,该指令将原型继承父作用域。如果设置scope:false,则该指令将使用父作用域。最后,如果你设置范围:{...},它将创建一个孤立的范围。

&#13;
&#13;
var app = angular.module("test",[]);

app.controller("myCntrl",function($scope){
    $scope.text = "Im in controller Scope";
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: true,
        template: "<div>Where are you, directive ? {{text}}</div>"
    };
});
&#13;
h2 {
    cursor: pointer;
}
.directive {
    border: 5px solid #F5BF6E;
    padding: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="test">
    
    <div ng-controller="myCntrl">
        <h2 ng-click="reverseName()">Where are you ? {{text}}</h2>
        <div my-directive class='directive'></div>
    </div>
</div>
&#13;
&#13;
&#13;

您可以查看此链接了解详情:Directive Scopes