【问题标题】:AngularJS - pass parameter from ng-repeat to controller from custom directiveAngularJS - 从自定义指令将参数从 ng-repeat 传递给控制器
【发布时间】:2017-01-01 13:30:13
【问题描述】:

我有一个自定义的 AngularJS 指令,它正在呈现一个 ng-repeat。在这个 ng-repeat 中,我想将一个元素传递给一个函数。该函数被调用,但项目未定义。

重要提示:我让我的人进行休息通话。

//Inside the template
<ul class="list-group" data-ng-repeat="person in persons track by $index">
<li>
... ng-click=fn(person) ...
</li>
</ul>

这是我喜欢传人的功能。

//in outside controller    
$scope.showPerson = function (item) {
    console.log(item) // this is undefined
}

我的指令如下所示:

directive('custom', function () {
    return {
        restrict: 'E',
        scope: {
            persons: "=persons",
            fn: "&"
        },
        templateUrl: "/views/templates/persons.html"
    };
});

我这样称呼我的指令:

<custom persons="persons" fn="showPerson()"></custom>

任何想法为什么项目未定义?我唯一能想到的是时间问题,因为指令在人员数组被填充之前触发(来自其余调用)。

【问题讨论】:

  • scope: { people: "=", } 与我创建的指令相比,一件事很快就脱颖而出。
  • 两个都可以写(如果是

标签: angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

在接受参数时,传递给独立作用域的函数有一个特殊性。首先,在 HTML 中定义参数:

<custom persons="persons" fn="showPerson(x)"></custom>

注意参数名称:x。现在从指令的模板中(这是特殊性):

<button ng-click="fn({x: person})" ...>

其中x 是上面定义的参数的名称。

【讨论】: