2017-01-19 96 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,我更新了我的答案,並在指令中添加了一個範圍綁定。我希望這將解決它。讓我知道它.. –

相關問題