我有两个指令,我想计算父亲标签中有多少个儿子,并在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/false
在directiveFather
(参见 demo 1 )或
“手动”编译、链接 HTML 并将其附加到 directiveFather
元素(参见 demo 2 )。
(还有使用嵌入的 Wildhoney's suggestion 和 template
。)
<子>
基本上,您不需要任何这些方法来工作 - 它们只需要证明一切正常(通过在 View 中显示计数器),但即使不附加计数器,addChild()
函数按预期被调用。
也就是说,在修复元素名称( <directive-father>
和 <directive-son>
)后,它会按预期工作。
关于javascript - 使用其他指令的指令 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25752991/