我的指示工作正常,但我想在let some2 = (all.a ? {a: "foo"} : {}) as SomeOptional
中使用它但是,链接内部的功能无法触发。
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');
}
},
}
});
答案 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;
}
}