【问题标题】:ng-click inside ng-repeat doesnt workng-click 内 ng-repeat 不起作用
【发布时间】:2016-06-04 17:48:14
【问题描述】:

我有一个看起来像下面的 html,在两种情况下我都有 2x ng-click 在整个代码中调用相同的函数。这两个函数都在同一个控制器中。

          <div class="tagselect tagselect--frameless">
            <div class="combobox__body combobox__body--open combobox__body--frameless" ng-show="focus">
                <ul class="list-unstyled">
                    <li class="combobox__item" ng-repeat="pos in listCtrl.positions | filter:query as results"
                        ng-click="listCtrl.choosePosition(pos)">{{pos.name}}
                    </li>
                </ul>
            </div>
          </div>
          <div class="col-md-2 no-padding">
            <button type="button" class="btn btn-success" ng-click="listCtrl.chosenPositions(789456)">Add</button>
          </div>

控制器看起来像:

myApp.controller('ListCtrl', ['$scope', '$cookies', '$http', function ($scope, $cookies, $http) {

    var listCtrl = {
        candidates: [],
        positions: [],
        chosenPositions: [],

        init: function () {
            listCtrl.getCandidates();
            listCtrl.getPositions();
        },
        getCandidates: function () {
            $http.get('candidates.json').then(function (res) {
                listCtrl.candidates = res.data;
            });
        },
        getPositions: function () {
            $http.get('positions.json').then(function (res) {
                listCtrl.positions = res.data;
            });
        },
        choosePosition: function (position) {
           console.log(position);
        }

    };

    listCtrl.init();
    $scope.listCtrl = listCtrl;
}]);

我仔细检查拼写错误并确保它不是因为功能(我用简单的控制台日志创建了一个新的)。

问题是按钮单击正确调用函数但 ng-repeat &lt;li ng-click=""&gt; 没有做任何事情。我在 Angular 文档中读到 ng-repeat 创建新范围,但在我看来,只要我使用对对象 listCtrlchoosePosition() 的引用,这应该仍然没问题@

谁能告诉我我做错了什么? 谢谢

编辑:Plunker 示例: http://plnkr.co/edit/ooUQA2n1Vyj8RZtsQ1Pj?p=preview

【问题讨论】:

  • 似乎 ng repeat 返回的 pos 是一个对象,但是,有效的调用: listCtrl.chosenPositions(789456) 正在接收一个原语,所以我认为你应该做 ng-click=" ng-repeat 中的 listCtrl.choosePosition(pos.someProperty)
  • 嗨@ArturoMontaño 你是对的,如果这个函数能做任何事情,但就像现在它只是console.log 它得到的值(我不知道,我很抱歉)。还有一个问题是,如果我在函数内部使用断点,它甚至没有进入函数内部

标签: angularjs


【解决方案1】:

ng-blur 正在做一些奇怪的事情,所以我建议您将 $scope.focus 的值从 ListCtrl 更改为,而不是使用 ng-blur

html 文件

<!-- more html code -->
<!-- input without ng-blur directive -->
<input class="tagselect__input" placeholder="Position" ng-focus="focus=true" ng-model="query">
<!-- more html code -->
<li class="combobox__item" ng-repeat="pos in listCtrl.positions | filter:query as results" ng-click="listCtrl.choosePosition(pos)">{{pos.name}}
<!-- more html code -->

js 文件

// more code goes here.
choosePosition: function (position) {
  //alert('Going to choosen position');
  //$scope.query = position.name;
  $scope.focus = false; // Hide div options from here.
  // rest of your code.
},
// more code goes here.

在这个plunkr工作

【讨论】: