2017-01-19 188 views
0

范围内假设下面的蓝图代码:访问主控制器从指令

<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 ....

回答

0

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

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>" 
 
    }; 
 
});
h2 { 
 
    cursor: pointer; 
 
} 
 
.directive { 
 
    border: 5px solid #F5BF6E; 
 
    padding: 10px; 
 
}
<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>

您可以检查此链接查看更多细节:在指令使用require,像Directive Scopes

+1

在回答之前,请先阅读问题! –

+0

如果你阅读我的答案,它会帮助你。如果你继承了范围,你可以访问父范围,在这种情况下,它是你的控制器的范围。 –

+0

@ILIAS,你在找什么?从指令访问控制器的范围.... –

2

最简单的方法可能是:

<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(); 
    } 
    }; 
}); 
+0

是的你是对的。但是,我忘记提及(我的蓝图不准确),我正在使用ui-routing。因此,没有ng控制器。整个页面通过ui-routing绑定到myCtrl。对于这种情况的任何想法?谢谢 –

+0

@ILIAS,我更新了我的答案,并在指令中添加了一个范围绑定。我希望这将解决它。让我知道它.. –

相关问题