javascript - 从指令链接传递范围变量

标签 javascript angularjs

我制作了一个 angularjs 指令,如下所示:

angular.module('myApp')
.driective('myDirective', function(){
 return {
  templateUrl: 'directive.html',
      restrict: 'E',
      scope: {
        'dirObj': '=object'
      },
      link: function (scope, element, attrs) {
        scope.message = "View Message";

        element.bind('mouseenter', function(){
          scope.overState = true;
          console.log('enter');
        });

        element.bind('mouseleave', function(){
          scope.overState = false;
          console.log('leave');
        });

      }
};
});

以及directive.html内部:

<h1>{{ message }}</h1>
<div ng-show="overState">This text doesn't appear!!!</div>

这是 plunkr 上的实时代码

问题是 element.bin 内的范围没有设置变量“overState”的值,有人可以解释一下为什么会发生这种情况以及如何修复它。

最佳答案

您需要使用$scope.$apply:

scope.$apply(function() { 
    scope.overState = true;
});

Angular 会自动包装大部分内置指令,因此它将通过摘要循环进行更新,但如果您绑定(bind)自己的事件(即 mouseentermouseleave),需要自己关闭摘要循环。

Updated Plnkr

<小时/>

根据以下评论进行更新

您还可以使用内置的 Angular Directive(指令) ng-mouseenterng-mouseleave,然后您无需担心自己评估 Angular 表达式。

<div class="directive-area" 
     ng-mouseleave="overState = false" 
     ng-mouseenter="overState = true">
  <h1>{{ message }}</h1>
  <div ng-show="overState">Test Text</div>
</div>

Built-in Directives Plnkr

关于javascript - 从指令链接传递范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529101/

相关文章:

javascript - 是否可以在 Canvas 中获取位置,其中 canvas 是 css 固定元素?

angularjs - 如何在 AngularJS 中使用 ng-repeat 创建嵌套结构

javascript - Angular ui路由器不区分大小写的查询参数

javascript - 单击后折叠导航栏保持打开状态

AngularJS:在 Electron 中检索 mysql 数据并将其发布到 AngularJS 范围

javascript - 您如何模拟作为函数的 Angular 服务?

javascript - 异步过滤 Promise 数组

javascript - 使用 devexpress 在 IE 上滚动条

javascript - 需要帮助以使用下拉选择列表来更改页面上的动态内容

javascript - Vite/Vue 3 : "require is not defined" when using image source as props