我在这样的指令中创建了一个新的作用域
controllersModule.directive('uploadBox', function() {
return {
restrict: 'E',
scope: {
topic: '=topic',
label: '=label'
},
templateUrl: '/assets/directives/uploadBox.html'
};});
并像这样使用此指令(值 -label 和 topic- 都是值,存储在 JSON 文件中,位于两个不同的 Controller 中)
<upload-box label="lc.getTerm('system_upload')" topic="tc.currentTopic.uID"></upload-box>
因此属性标签和主题都传递到新的(创建的)范围。现在,有趣的是,虽然我能够访问模板 HTML 文件 (uploadBox.html) 中的两个值
<div ng-controller="DropUploadCtrl">
<button class="btn btn-success" dropzone="dropzoneConfig">
<!-- label is correctly shown -->
{{ label }}
</button>
<!-- this link works fine: Evaluates to something like aaa/54dg54...SHA128-Hash...G4FX-->
<a ng-href="aaa/{{ topic }}">BB</a>
</div>
只能从 DropUploadController 中访问标签值。
controllersModule.controller('DropUploadCtrl', ['$scope',function($scope) {
var that = this;
console.log($scope.label); // this is working fine
console.log($scope.topic); // this is undefined
// some more stuff here
}]);
我知道作用域是为特定 Controller 创建的,您不能直接在两个 Controller 之间共享作用域变量。但是,我认为这不是问题,因为我可以使用标签值。但是,我的代码哪里错了?
非常感谢
编辑:
Controller 内 rootScope 的输出
console.log("$scope::>");
console.log($scope.label);
console.log($scope.topic);
console.log("$rootScope::>")
console.log($rootScope.label);
console.log($rootScope.topic);
看起来像这样:
"$scope::>"
"I'm a label"
undefined
"$rootScope::>"
undefined
undefined
此外,该值在指令的链接函数中未定义
Edit2:解决方案已找到! 在另一个 Controller 初始化时,tc.currentTopic.uID 中的值尚未填充。这就是表达式 {{topic}} 工作正常的原因,因为当值发生变化时,几毫秒后它会被再次计算。我现在直接通过 $routeParams 获取数据。
最佳答案
指令具有独立的范围。由于您添加了:
scope: {
topic: '=topic',
label: '=label'
},
它创建了一个隔离的范围。
但是, Angular 文档说:
=
或=attr
- 在本地范围属性和通过 attr 属性的值定义的名称的父范围属性之间设置双向绑定(bind)。如果未指定属性名称,则假定属性名称与本地名称相同。鉴于<widget my-attr="parentModel">
和小部件范围定义:{ localModel:'=myAttr' }
,那么小部件范围属性 localModel 将反射(reflect) parentModel
的值在父范围上。对 parentModel
的任何更改将反射(reflect)在 localModel
localModel 中的任何更改都将反射(reflect)在 parentModel
中。
链接 here
关于javascript - AngularJS: Controller 内未定义范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27786188/