我试图从指令的链接或控制器功能访问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>
为什么不从显示模式范围传递测试?我在这里做错了什么?
答案 0 :(得分:0)
您在错误的地方定义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) {
}
};
});