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

时间:2016-04-16 00:59:52

标签: javascript angularjs

我的指示工作正常,但我想在let some2 = (all.a ? {a: "foo"} : {}) as SomeOptional 中使用它但是,链接内部的功能无法触发。

http://jsfiddle.net/ovzyro1f/

some2.a

JS

ng-click

我想在ng-click中调用该函数,请参阅此http://jsfiddle.net/ovzyro1f/2/以删除<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>

中的同胞
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');
      }
    },
  }
});

1 个答案:

答案 0 :(得分:1)

你应该避免像在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;
  }

}