我是角色的书呆子,创建一个基本的TODO应用程序。在此我试图在鼠标进入delete
项目时显示li
,该项目是通过todoListItem
指令呈现的。我还有另外两个指令mouseEnter
和mouseLeave
,mouseEnter
如何更改todo.showDelete
?
angular.module('ToDo.directives', [])
.directive('todoListItem', function() {
return {
restrict: 'E',
template: "<li mouse-enter mouse-leave ng-repeat='todo in Todos | filter:searchText' class='todoList' ><input type='checkbox' ng-model='todo.done' /> <i ng-class=(todo.done) ? 'lineThrough' : ''>{{todo.text}}</i><a ng-show='todo.showDelete' >D</a></li>"
};
})
.directive("mouseEnter", function () {
return function (scope, element, attrs) {
element.bind("mouseenter", function () {
// how can i change `todo.showDelete` from here ?
})
}
})
.directive("mouseLeave", function () {
return function (scope, element, attrs) {
element.bind("mouseleave", function () {
// how can i change `todo.showDelete` from here ?
})
}
});
答案 0 :(得分:1)
您可以在指令中使用Angular的双向绑定,并具有以下内容:
angular.module('ToDo.directives', [])
.directive('todoListItem', function() {
return {
restrict: 'E',
scope:{
"todo":"="
},
template: "<li mouse-enter mouse-leave ng-repeat='todo in Todos | filter:searchText' class='todoList' ><input type='checkbox' ng-model='todo.done' /> <i ng-class=(todo.done) ? 'lineThrough' : ''>{{todo.text}}</i><a ng-show='todo.showDelete' >D</a></li>"
};
})
.directive("mouseEnter", function () {
return function (scope, element, attrs) {
element.bind("mouseenter", function () {
// how can i change `todo.showDelete` from here ?
})
}
})
.directive("mouseLeave", function () {
return function (scope, element, attrs) {
element.bind("mouseleave", function () {
// how can i change `todo.showDelete` from here ?
})
}
});
在HTML中你需要有这样的东西:
<todo-list-item todo="todo"></todo-list-item>
现在你可以在指令中更改范围的todo变量,它也将反映在指令之外。