【问题标题】:Access scope from link function in directive AngularJs?从指令AngularJs中的链接函数访问范围?
【发布时间】:2017-04-15 06:55:05
【问题描述】:

我正在尝试从指令的链接或控制器功能访问 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 数组属于您的指令,那么您不需要使用隔离范围来获取它。您可以简单地使用$scope.tests 来检索它。如果它属于父控制器,那么请看下面@32teeth 的回答
  • 指令控制器和指令链接函数访问指令的 isolate child 范围。指令双向= 绑定属性访问parent 范围变量。有关详细信息,请参阅AngularJS Developer Guide - Isolating the Scope of a Directive

标签: javascript angularjs angularjs-directive angular-directive


【解决方案1】:

你在错误的地方定义了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) {
        }
    };
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多