【问题标题】:undefined ng-repeat variable when passed from directive template to a controller从指令模板传递到控制器时未定义的 ng-repeat 变量
【发布时间】:2017-05-20 11:53:06
【问题描述】:

我有一个带有模板的指令,该模板在锚标记上使用 ng-repeat 创建锚库。每个锚点也有一个 ng-click,当点击它时会调用父控制器函数。向此函数传递 ng-repeat 项。

问题:在父控制器方法中访问该项目时未定义

这是一个模拟类似情况的测试场景

<testdirective func="show(x)" items="buttons"></testdirective>

http://plnkr.co/edit/43aNqFS71Jn9vOdh6AG2?p=preview

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您需要进行两项更改。

    在您的 index.html 中引用您的函数:

        <testdirective func="show" items="buttons"></testdirective>
    

    并在您的 testdirective 中更改您的模板,如下所示:

      template: '<button ng-repeat="item in items" ng-click="func()(item)" id="submit" />{{item}}</button>',
    

    注意 ng-click 的变化 - 第一个括号是对函数本身的引用,第二个是使用参数调用函数。

    我还对你的 plunker 做了一个分叉: http://plnkr.co/edit/nECPbL8YoToi0jP9HJHQ?p=preview

    请告诉我这是否是您想要实现的目标

    【讨论】:

    • 太棒了!你从哪里得到这个技巧:)。我搜索了一遍,没有找到任何对这种参数传递的引用。非常感谢。
    【解决方案2】:

    你的指令应该绑定到一个控制器,改变它如下,

    app.directive("testdirective", function() {
      return {
        restrict: "E",
        controller: 'testController',
        template: '<button ng-repeat="item in items" ng-click="show(item)" id="submit" />{{item}}</button>',
        scope: {
          items: "=",
          func: '&'
        }
    
      };
    });
    

    演示

    // Code goes here
    
    var app = angular.module('test', []);
    
    app.controller('testController', function($scope) {
    
      $scope.buttons = ['b1', 'b2', 'b3', 'b4', 'b5'];
    
      $scope.show = function(x) {
        alert(x);
      }
    })
    
    
    app.directive("testdirective", function() {
      return {
        restrict: "E",
        controller: 'testController',
        template: '<button ng-repeat="item in items" ng-click="show(item)" id="submit" />{{item}}</button>',
        scope: {
          items: "=",
          func: '&'
        }
    
      };
    });
    <!DOCTYPE html>
    <html ng-app='test'>
    
      <head>
        <script data-require="angular.js@*" data-semver="1.3.0-rc.1" src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
    
      <body>
      <div ng-controller="testController">
        <h1>Hello Plunker!</h1> {{ testValue }}
        
        <testdirective func="show(x)" items="buttons"></testdirective>
        </div>
    </body>
    </html>

    【讨论】:

    • 是的,我明白,但这不是一个可重用的指令,因为它不是绑定到控制器的。
    • 不可重用是什么意思?不,你可以重复使用它
    • 您已将其显式绑定到 controller: 'testController',因此它是紧密耦合的。
    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多