无法读取控制器中的指令值
Cannot read directive value in controller
尝试实现一个可以从其grid-url
指令读取URL参数的表。稍后,这个将提供给控制器中的$http
。然而,它似乎并没有像预期的那样工作。值总是undefined
标记如下:
<table class="table table-striped" grid-url="http://localhost/records/all">
...
</table>
下面是相关的初始化代码片段:
app.directive('gridUrl', function(){
return {
replace: true,
link: function(scope, element, attrs){
// Add the gridUrl property to the scope
scope.gridUrl = attrs.gridUrl;
}
}
});
app.controller('Ctrl', function($scope){
// Expect to get http://localhost/records/all, but get undefined instead
console.log($scope.gridUrl);
});
看起来不像是作用域隔离的问题。当在控制器本身调用console.log($scope)
时,最奇怪的事情是我可以看到$scope.gridUrl
有http://localhost/records/all
。
gridUrl
在控制器中未定义呢? 你应该在控制器中定义gridUrl
,然后用你的指令绑定它:
<div ng-controller="Ctrl" ng-init="$scope.gridUrlAttr = 'http://localhost/records/all'">
<table class="table table-striped" grid-url-attr="$scope.gridUrlAttr">
...
</table>
</div>
app.directive('gridUrl', function(){
return {
replace: true,
scope: {
gridUrlAttr: "="
},
link: function(scope, element, attrs){
// Add the gridUrl property to the scope
console.log(scope.gridUrlAttr);
// here you can change the gridUrlAttr value
}
}
});
app.controller('Ctrl', function($scope){
// Expect to get http://localhost/records/all, but get undefined instead
console.log($scope.gridUrlAttr);
});
首先定义控制器。所以在作用域中没有属性gridl。你必须使用共享服务将指令注入到控制器中。
您可以使用service在模块之间共享数据:
app.factory('SharedService', function() {
return {
sharedObject: {
value: ''
}
};
});`
这是因为先调用了控制器,然后才编译了指令。因此,gridUri值在控制器调用后的几个周期内到达作用域。
证明你可以在模板中输出这个变量:
<table class="table table-striped" grid-url="http://localhost/records/all">
test :: {{ gridUrl }}
</table>
登录到控制台后,它将显示$作用域中的属性。(当它是一个对象时,它在控制台中更新)
根据你需要这个变量的目的,你可以把手表放在它上面,当它出现在作用域中时触发一些动作,或者你可以重新设计你提供数据的方式(例如,添加一些共享的UI模型服务)
找到了在保持结构不变的情况下使其成为可能的方法。这里的技巧是在10毫秒内使用$timeout
服务。
app.controller('Ctrl', function($scope, $timeout){
$timeout(function(){
// Getting http://localhost/records/all as expected
console.log($scope.gridUrl);
}, 10);
});
相关文章:
- 在指令控制器中使用$attrs时出现问题
- Angular,从指令控制器中的控制器触发函数
- 角度指令控制器:参数不是函数,未定义
- 如何将值传递到角度中的指令控制器
- angularjs+ui.router:指令控制器和链接函数之间的不同行为
- 如何使用角度指令控制器动态单击复选框
- 如何从父指令/控制器访问指令范围
- 角度指令 - 需要从指令控制器访问所需的控制器
- 指令链接中的范围变量不会更新到指令控制器使用 Angular 读取它时
- 从链接函数修改指令控制器变量
- 监视指令控制器不工作
- Angular js 指令控制器访问范围属性,但返回未定义
- 指令控制器和普通控制器之间的区别
- 角度指令链接函数中的范围是否与角度指令控制器中的$scope相同
- AngularJS :如何从相同的指令控制器访问指令范围
- 角度“这个”在指令控制器内不起作用
- 列出 AngularJS 模块中声明的指令/控制器
- 角度指令控制器单元测试使用窗口.确认
- 从指令控制器到控制器的角度共享数据
- UI 引导程序自定义指令控制器不是一个函数