javascript - 已编译的子指令已附加到父级但无法访问父级作用域?

标签 javascript angularjs

我创建了 2 个指令,一个用于显示框(confirmedBox 指令),另一个用于显示该框(confirmingBox)。在 confirmingBox 的链接函数内部,我通过使用父作用域 confirmingBox 进行编译创建了 confirmedBox。但是,当单击“显示框”按钮时,它会记录 isDisplay undefined,这意味着我无法对变量 isDisplay 从父指令到子指令进行 2 路绑定(bind)。我不知道为什么它不起作用?

实时代码: http://plnkr.co/edit/SHH1JEtGJxibyem25kfd?p=preview

JavaScript 代码:

angular.module('AppA2_Task',[])
.directive('confirmedClick', function ($compile, $rootScope) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.displayBox = true;
            element.on('click', function () {
                element.attr('disabled', 'disabled');
                var boxScope = $rootScope.$new(true, scope);
                var boxElem = $compile('<div data-confirming-box data-confirm="confirm" data-is-displayed="displayBox"></div>')(boxScope);
                element.append(boxElem);
                scope.$apply(function () {
                    scope.displayBox = true;
                });
            });
        }
    }
})
.directive('confirmingBox', function () {
    return {
        //require: '^confirmedClick',
        restrict: 'A',
        template: "<div ng-if='isDisplayed'>I am a box</div>",
        scope: {
            isDisplayed: '='
        },
        link : function(scope){
          console.log('isDisplayed',scope.isDisplayed);
        }
    }
})
.controller('MainController', function () {

});

代码 html

<body data-ng-controller="MainController">
    <button data-confirmed-click>Show box</button>
</body>

最佳答案

您正在将模板与 boxScope 链接,但在 scope 上设置 displayBox = true

将其更改为:

boxScope.displayBox = true;

您还需要在编译和链接之前执行此操作,否则在执行confirmingBox的链接函数时将出现undefined

最后,要么调用末尾不带参数的 scope.$apply(),要么用它包装 click 函数中的所有内容。

我更喜欢第二种选择,因为 Angular 会将其内部包装在 try...catch block 中,并且发生的任何异常都将传递给 $exceptionHandler服务。

示例:

link: function(scope, element, attrs) {
  element.on('click', function() {
    scope.$apply(function() {
      element.attr('disabled', 'disabled');
      var boxScope = $rootScope.$new(true, scope);
      boxScope.displayBox = true;
      var boxElem = $compile('<div data-confirming-box data-confirm="confirm" data-is-displayed="displayBox"></div>')(boxScope);
      element.append(boxElem);
    });
  });
}

演示: http://plnkr.co/edit/OwcgD0NntVo3DhTVvXmA?p=preview

关于javascript - 已编译的子指令已附加到父级但无法访问父级作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817882/

相关文章:

javascript - 当我们想要订阅可观察数组时如何进行错误处理

javascript - AngularJS ng-click 表行但不单击某个 td

angularjs - 406( Not Acceptable )在 Rails 4 中使用 AngularJS

Javascript 动态输入掩码

javascript - 当我使用 js 更改 className 时,css 转换不起作用

javascript - 如何通过 React 使用 Google Map Places API?

javascript - 如何在 Ionic 应用程序中以正确的方式准备好设备?

javascript - 指令内的按钮未被禁用

javascript - 按天应用 View 中的 Controller 数据

javascript - 从 highcharts.js 中的 axisX 中删除月份