[英]angular change variable from directive
我試圖用angularJS創建類似於Google日歷的日歷,但遇到了問題。 我在屏幕上添加了事件,並且我的html看起來像這樣
<ul drop-event id="0">
<li move-event></li>
</ul>
<ul drop-event id="1">
<li move-event></li>
</ul>
..等42框顯示1個月。 我創建了一個指令drop-event
,我希望它可以作為droppable並在將鼠標懸停在它上時從<ul>
的id
獲取ID。 到目前為止,我做到了
myApp.directive('dropEvent', function() {
return {
restrict: 'A',
link: function(scope, elem, attr) {
elem.bind('mouseenter', function() {
scope.theHover = elem.attr("id");
});
elem.droppable({ tolerance: "pointer" });
elem.bind('drop', function(event, ui) {
// future stuff
});
}
};
});
但是問題是,當我嘗試使用scope.theHover = elem.attr("id");
更改theHover
變量時,它不會更改為控制器scope.theHover = elem.attr("id");
在指令中。
第二個問題是,如果我將鼠標懸停在<ul>
的子元素<li>
上,則mouseenter不會傳播到<ul>
。
有沒有辦法讓它傳播到父級,有沒有辦法將theHover從指令更改為控制器?
提前謝謝你,丹尼爾!
由於您是在DOM事件中更新變量: elem.bind('mouseenter', function() {...}
Angular不知道變量已更改。要知道,請將代碼包裝在$apply
像這樣$apply
:
scope.$apply(function() {
scope.theHover = elem.attr("id");
});
然后,您的控制器可以像這樣監視theHover
更改:
myApp.controller('myCtrl', function ($scope) {
$scope.$watch('theHover', function (newValue,oldValue) {
console.log("hover ",newValue);
});
});
演示小提琴 -Mouseenter在完整的<ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.