我的指令工作正常,但我想在 ng-click
中使用它,但是无法触发链接内的函数。
<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');
}
},
}
});
我想调用ng-click中的函数,请看这个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 )。大多数时候您无需手动进行更改。
这样做时,通常不需要使用链接功能。您可以拥有一个 Controller (如您的示例中所示)或带有 Controller 的指令( https://docs.angularjs.org/guide/directive )。
最后我只是修改了一点你的 Controller 和模板。
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;
}
}
关于javascript - ng-click中Angularjs指令链接调用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659044/