Angularjs指令链接调用ng-click中的函数



我的指令运行良好,但我想在ng-click中使用它。但是,链接内的函数无法触发。

http://jsfiddle.net/ovzyro1f/

<div ng-app="editer" ng-controller="myCtrl" class="container">
  <div class="parents">
    <div ng-repeat="item in items" class="wrap" sibs>
      <span>{{item.name}}</span>
      <button ng-click="">click</button>
    </div>
  </div>
</div>

JS-

function myCtrl($scope) {
  $scope.editedItem = null;
  $scope.items = [{
    name: "item #1",
    thing: "thing 1"
  }, {
    name: "item #2",
    thing: "thing 2"
  }, {
    name: "item #3",
    thing: "thing 3"
  }];
  $scope.show = false; //ignore this line
}
var editer = angular.module('editer', []);
editer.directive('sibs', function() {
  return {
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        element.parent().children().addClass('unclicked');
        element.removeClass('unclicked');
      })
      scope.myClick = function() {
        element.parent().children().addClass('unclicked');
        element.removeClass('unclicked');
      }
    },
  }
});

我想点击调用函数,请看这个http://jsfiddle.net/ovzyro1f/2/从div ng-repeat="item in items" class="wrap" 中删除同胞

 <button ng-click="myClick()">click</button> 

您应该避免像在jQuery中那样操作DOM。

在Angular中,我们的想法不同:当数据发生变化时,数据会自动转换DOM(https://docs.angularjs.org/guide/databinding)。大多数时候,您不必手动进行更改。

在执行此操作时,通常不需要使用链接函数。您可以有一个控制器(如您的示例)或一个带有控制器的指令(https://docs.angularjs.org/guide/directive)。

最后,我只是修改了你的控制器和模板。

HTML

<div ng-app="editer" ng-controller="myCtrl" class="container">
  <div class="parents">
    <div ng-repeat="item in items" class="wrap" sibs>
      <span ng-class="{ unclicked: !item.selected }">{{ item.name }}</span>
      <button ng-click="selectItem(item)">click</button>
    </div>
  </div>
</div>

JS

function myCtrl($scope) {
  $scope.items = [...];
  $scope.selectItem = function (item) {
      // reset all the items
      $scope.items.forEach(function (i) {
          i.selected = false;
      });
      // set the new selected item
      item.selected = true;
  }
}

最新更新