简体   繁体   中英

Angularjs directive link call function in ng-click

My directive works fine, but I'd like to use it in ng-click However, the function inside link can't be triggered.

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');
      }
    },
  }
});

I'd like to call the function in ng-click please see this one http://jsfiddle.net/ovzyro1f/2/ to remove sib from div ng-repeat="item in items" class="wrap"

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

You should avoid to manipulate the DOM like we do in jQuery.

In Angular we think differently: it's the data which transforms automatically the DOM when the data changes ( https://docs.angularjs.org/guide/databinding ). Most of the time you never have to make the changes manually.

In doing so, you generally don't need to use the link function. You can have a controller (like in your example) or a directive with a controller ( https://docs.angularjs.org/guide/directive ).

Finally I just modified a little bit your controller and your template.

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;
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM