![](/img/trans.png)
[英]How to access scope in a function inside link function in angularjs directive?
[英]Access scope from link function in directive AngularJs?
我正在嘗試從指令的鏈接或控制器功能以ng-repeat訪問數據。 我的指令代碼如下所示。
app.directive('ssLeftNavDirective', function($rootScope) {
// Runs during compile
return {
templateUrl: 'leftnavmenu.html',
scope: {
displayMode: '='
},
controller: function($scope) {
$scope.tests = ['health check', 'Performance Monitor', 'Compare Test', 'API Helpdesk'];
$scope.troubleshooting = ['Trouble Shooting 1', 'Trouble Shooting 2', 'Trouble Shooting 3'];
$scope.help = ['Help 1', 'Help 2', 'Help 3'];
$scope.settings = ['Settings 1', 'Settings 2', 'Settings 3'];
},
link: function($scope, iElm, iAttrs, controller) {
$scope.menuDisplayed = true;
$scope.tests = ['health check', 'Performance Monitor', 'Compare Test', 'API Helpdesk'];
$scope.troubleshooting = ['Trouble Shooting 1', 'Trouble Shooting 2', 'Trouble Shooting 3'];
$scope.help = ['Help 1', 'Help 2', 'Help 3'];
$scope.settings = ['Settings 1', 'Settings 2', 'Settings 3'];
}
};
});
我在控制器和鏈接中都添加了它,以對其進行測試。
這是指令模板:
<div id="menudiv">
<nav id="leftnavmenu" ng-class="menuDisplayed ? 'navon' : 'navoff'">
<a href="#" ng-repeat="nav in displayMode">{{nav}}</a>
</nav>
<i class="fa hamburgermenu" aria-hidden="true"
ng-class="menuDisplayed ? 'menuon fa-times' : 'menuoff fa-bars'"
ng-click="menuDisplayed = !menuDisplayed">
</i>
在主HTML中,我像這樣添加指令和范圍值。
<ss-left-nav-directive display-mode="tests"></ss-left-nav-directive>
為什么不從顯示模式范圍通過測試? 我在這里做錯了什么?
您在錯誤的位置定義tests
。 與其在鏈接功能或指令的控制器中定義它,不如在使用該指令的模板的控制器中定義它。 因此對於 ,
<div ng-controller="AppController">
<ss-left-nav-directive display-mode="tests"></ss-left-nav-directive>
</div>
在AppController中(或綁定到哪個控制器tests
),
app.controller('AppController', function ($scope) {
$scope.tests = ['health check', 'Performance Monitor', 'Compare Test', 'API Helpdesk'];
});
下面的指令應該起作用,
app.directive('ssLeftNavDirective', function ($rootScope) {
// Runs during compile
return {
templateUrl: 'leftnavmenu.html',
scope: {
displayMode: '='
},
controller: function ($scope) {
$scope.menuDisplayed = true;
},
link: function ($scope, iElm, iAttrs, controller) {
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.