Angularjs 使用不同的作用域定义将“ng init”的有线作用域置于自定义指令之外
这来自angular doc关于Angularjs 使用不同的作用域定义将“ng init”的有线作用域置于自定义指令之外,angularjs,directive,ng-init,Angularjs,Directive,Ng Init,这来自angular doc关于ng init ngInit指令允许您计算当前范围内的表达式 但是如果我将ng init与自定义指令一起使用,并且该指令使用不同的范围定义,那么ng init的变量将具有不同的范围 排除:test:{{test}test2:{{test2}}test3:{test3} 排除:test:{{test}test2:{{test2}}test3:{test3} 角度模块('transcludeScope',[]) .指令('truescope',函数(){ 返回{
ng init
ngInit指令允许您计算当前范围内的表达式
但是如果我将ng init
与自定义指令一起使用,并且该指令使用不同的范围定义,那么ng init
的变量将具有不同的范围
排除:test:{{test}test2:{{test2}}test3:{test3}
排除:test:{{test}test2:{{test2}}test3:{test3}
角度模块('transcludeScope',[])
.指令('truescope',函数(){
返回{
是的,
范围:正确,
模板:“test:{{test}test2:{{test2}}”
}
})
.directive('isolatescope',function(){
返回{
是的,
作用域:{},
模板:“test:{{test}}test3:{{test3}}”
}
});
从结果来看,test2
仅在指令内部可用,而test3
在整个应用程序中可用
有人能解释他们的行为吗?谢谢:-)您完全忽略了文档页面上复制描述的巨大红色警告消息
ngInit
是一个指令,优先级为450,这意味着它在与其他指令交互时,尤其是与优先级较低的指令交互时,可能会产生不希望的副作用,或者自己创建子作用域。@Claies我遵循实际项目代码中ng doc中的警告建议,当我创建一个演示代码来解释指令的作用域时,就会出现这个问题,我不使用任何控制器,因为这个演示使用控制器非常简单。@Claies这可能是一个副作用……我实际上不认为这与ngInit
,而是与transclude
如何与作用域:{}
交互有关。这可能会给你更多的洞察力:@tjfdfs这也可能对你有所帮助。
<body ng-app="transcludeScope" ng-init="test='test'">
<div truescope ng-init="test2='test2'">Transcluded:<p>test: {{test}}</p><p>test2: {{test2}}</p><p>test3: {{test3}}</p></div>
<hr>
<div isolatescope ng-init="test3='test3'">Transcluded:<p>test: {{test}}</p><p>test2: {{test2}}</p><p>test3: {{test3}}</p></div>
</div>
</body>
angular.module('transcludeScope', [])
.directive('truescope', function() {
return {
transclude: true,
scope: true,
template: "<p>test: {{test}}</p><p>test2: {{test2}}</p><div ng-transclude></div>"
}
})
.directive('isolatescope', function() {
return {
transclude: true,
scope: {},
template: "<p>test: {{test}}</p><p>test3: {{test3}}</p><div ng-transclude></div>"
}
});