javascript - 使用其他指令的指令 - AngularJS

标签 javascript angularjs angularjs-directive

我有两个指令,我想计算父亲标签中有多少个儿子,并在index.html中显示计数器,如JS文件后所示,问题是我没有正确获取数字

   module.directive('directiveFather', function () {

    return {

    restrict: 'E',
    scope: {},
    controller: function ($scope) {

        $scope.AllCounter = 0;

        this.addCounter = function () {

            $scope.AllCounter = $scope.AllCounter + 1;

        }

    }


}

})

  module.directive('directiveSon', function () {

return {

    restrict: 'E',
    scope: {},
    require: '^directiveFather',
    link: function(scope, element, attrs, fatherCtrl){
      fatherCtrl.addCounter();
     }
    }


}

})

<directive father>

 <directive son>

 </directive son>
 {{AllCounter}}

 </directive father>

最佳答案

如果您使用隔离范围,则 directiveFather 内的元素将绑定(bind)到父范围(因此 AllCounter 在 View 中不会直接可用 - 尽管它将保存正确的值)。

<小时/>

您可以更改 scope: {}scope: true/falsedirectiveFather (参见 demo 1 )或
“手动”编译、链接 HTML 并将其附加到 directiveFather元素(参见 demo 2 )。
(还有使用嵌入的 Wildhoney's suggestiontemplate 。)

<子> 基本上,您不需要任何这些方法来工作 - 它们只需要证明一切正常(通过在 View 中显示计数器),但即使不附加计数器,addChild()函数按预期被调用。

<小时/>

也就是说,在修复元素名称( <directive-father><directive-son> )后,它会按预期工作。

<小时/>

另请参阅这些简短的演示: demo 1 , demo 2

关于javascript - 使用其他指令的指令 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25752991/

相关文章:

javascript - 使用带有 browserSettings.proxyConfig 的 firefox webextension 设置代理

javascript - HTML,CSS,JS 日历添加

javascript - 前端项目使用 npm 时避免 bundle 中的重复模块

angularjs - 如何使用 Passport Js 将 mongodb 用户迁移到 Couchdb?

javascript - AngularJs 使用指令中的输入字段验证表单

javascript - 如何在 Meteor + Ionic 应用程序中使用 Meteor 方法

javascript - Fabricjs:撤消时不呈现背景图像

javascript - 仅当 angularjs Accordion 打开时如何调用函数

javascript - ng-select 下拉 ajax/对象映射

angularjs - 无法在指令中获得 $error.maxlength 验证