简体   繁体   English

指令的角度变化变量

[英]angular change variable from directive

i am trying to create a calendar similar to google calendar with angularJS and i got into a problem. 我试图用angularJS创建类似于Google日历的日历,但遇到了问题。 I added the events on the screen and my html looks like this 我在屏幕上添加了事件,并且我的html看起来像这样

<ul drop-event id="0">
    <li move-event></li>
</ul>
<ul drop-event id="1">
    <li move-event></li>
</ul>

.. and so on 42 boxes to show 1 month. ..等42框显示1个月。 I created a directive drop-event which i would like to work as droppable and also when you hover mouse on it, to get the id from the id of the <ul> . 我创建了一个指令drop-event ,我希望它可以作为droppable并在将鼠标悬停在它上时从<ul>id获取ID。 So far i did it like this 到目前为止,我做到了

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

but the problem is that the theHover variable does not change into the controller when i try to change it with scope.theHover = elem.attr("id"); 但是问题是,当我尝试使用scope.theHover = elem.attr("id");更改theHover变量时,它不会更改为控制器scope.theHover = elem.attr("id"); inside the directive. 在指令中。

And the second problem i have is that if i hover on a <li> which is a child to the <ul> , the mouseenter does not propagate to the <ul> . 第二个问题是,如果我将鼠标悬停在<ul>的子元素<li>上,则mouseenter不会传播到<ul>

Is there a way to make it propagate to the parent, and is there a way to change the theHover from directive into the controller ? 有没有办法让它传播到父级,有没有办法将theHover从指令更改为控制器?

Thank you in advance, Daniel! 提前谢谢你,丹尼尔!

Since you're updating the variable inside a DOM event: elem.bind('mouseenter', function() {...} Angular doesn't know that the variable has changed. To make it aware, wrap your code in an $apply like this: 由于您是在DOM事件中更新变量: elem.bind('mouseenter', function() {...} Angular不知道变量已更改。要知道,请将代码包装在$apply像这样$apply

scope.$apply(function() {
   scope.theHover = elem.attr("id");
});

Then your controller can watch for changes to theHover like this: 然后,您的控制器可以像这样监视theHover更改:

myApp.controller('myCtrl', function ($scope) {
    $scope.$watch('theHover', function (newValue,oldValue) {
       console.log("hover ",newValue);
    });
});

Demo fiddle - with the mouseenter working on the full <ul> 演示小提琴 -Mouseenter在完整的<ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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