javascript - 与 rootScope 交互的指令在 Angular JS 中不起作用

标签 javascript angularjs

我正在尝试与 rootScope 进行交互,以便显示模态。我有一个非常基本的指令,我正在尝试将 rootScopeng-show 配对使用。

指令代码如下:

.directive('modal', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'A',
        templateUrl: 'view/templates/modal-confirm.tpl.html',
        link: function (scope, element, attrs) {
            console.log(scope);

            element.on('click', function() {
                scope.$root.confirmModal.isVisible = true;
                console.log('open modal');
            });
        }
    }
}])

当我记录 scope 变量时,它显示我已使用 isVisible: true 更新了 $root 但是,我的模式没有出现。如果我将 scope.$root.confirmModal.isVisible = true; 更改为 $rootScope.confirmModal.isVisible = true; 我得到相同的结果,console.log 是工作但没有模态出现。

这是模态模板的代码:

<!-- Confirm Modal Template -->
<div ng-if="$root.confirmModal.isVisible" class="overlay">
    <div class="overlay-content extended">
        <span>{{ $root.confirmModal.content }}</span>
        <div class="buttons">
            <button ng-click="$root.confirmModal.isVisible = false;" class="btn btn-default half">Cancel</button>
        </div>
    </div>
</div>

是否无法在指令中与 $rootScope 进行交互?

使用 scope 代替 $rootScope 更新代码:

.directive('modal', ['$rootScope', function ($rootScope) {
    return {
        restrict: 'A',
        templateUrl: 'view/templates/modal-confirm.tpl.html',
        link: function (scope, element, attrs) {
            scope.isVisible = false;

            element.on('click', function() {
                scope.isVisible = true;
                console.log(scope);
                console.log('open modal');
            });
        }
    }
}])

<!-- Confirm Modal Template -->
<div ng-if="isVisible" class="overlay">
    <div class="overlay-content extended">
        <span>hello world</span>
    </div>
</div>

但结果相同。

最佳答案

您并没有做错什么,您只是少了一行代码。在此声明中:

element.on('click', function() {
  scope.isVisible = true;
  console.log(scope);
  console.log('open modal');
});

您正在创建一个匿名函数,这非常好,但是 Angular 将无法自动神奇地跟踪对范围变量所做的更改。您需要做的是在函数结束时明确请求摘要循环将您的代码包装在 $apply 或 $timeout 函数中。像这样:

element.on('click', function() {
  scope.$apply(function(){ // or $timeout(function() {
    scope.isVisible = true;
    console.log(scope);
    console.log('open modal');
  });

});

如果您想了解有关 $apply 的更多信息,请查看此 great article .最后我组装了一个 Plunker here用你的代码让你能够测试。

关于javascript - 与 rootScope 交互的指令在 Angular JS 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935010/

相关文章:

javascript - 如何从 JavaScriptObject 读取 String[]? (GWT)

javascript - 使用ajax从 Node js服务器获取json信息

javascript - 在 Node.js 中删除/释放 Twilio 电话号码的语法是什么?

javascript - Bootstrap Modal 禁用来自子 DIV 的文本字段

angularjs - 关于使用 angularjs 或 vuejs 进行客户端路由的 SEO 方面

MVC 中的 javascript - 从另一个列表填充一个列表

javascript - 递归搜索 JSON 字符串字典,查找键值对在 "name"中的所有值

javascript - 具有不同数据的多个对象的一种表单和验证

javascript - 带有 jquery-confirm 的 Angular 应用程序。如何在模态中插入选择?

javascript - Angular 2 : property becomes underfined