问题描述
我有一个简单的问题,我认为它有一个非常简单的解决方案,但不知何故我错过了它.
I have a simple question that I think has a pretty simple solution, but somehow I am missing it.
我正在为我的应用设置一个简单的指令.我将 scope 属性设置为默认值false",因为我希望它共享我的控制器的范围.
I'm setting up a simple directive for my app. I'm leaving the scope property set to the default, "false", because I want it to share the scope of my controller.
问题是,我似乎无法访问该范围.
The problem is, I can't seem to access that scope.
在我的链接功能中,我可以:
In my linking function, I can do:
console.dir(scope)
并且我可以在范围对象中看到我所追求的属性('pages').
and I can see the property that I am after ('pages') in the scope object.
如果我尝试这样做:
console.dir(scope.pages)
然而,它返回未定义.
我错过了什么?
提前致谢.
MyDirectives.directive("mdPagination", function(){
return {
templateURL: "/templates/pagination.html",
replace: true,
restrict: 'A',
scope: false, //default
link: function(scope, element, attrs){
console.log('in linking function');
console.dir(scope);
console.dir(element);
console.dir(attrs);
console.dir(scope.pages);
}
}
});
模板:
<nav class="pagination" md-Pagination></nav>
控制器:
App.controller('MachinesListCtrl', function ($scope, $routeParams, $location, MachineServices, CustomerServices) {
var page = ($routeParams.page ? $routeParams.page : 1);
//if we are getting all machines based on their customer id.
if($routeParams.customerID){
MachineServices.getByCustomerId($routeParams.customerID).then(function (data) {
_.each(data.results, function (machine, index, list) {
CustomerServices.get(machine.customer_id).then(function(data){
machine.CustomerData = data.results;
});
});
$scope.Machines = data.results;
$scope.pages = data.pages;
});
}
//otherwise we just want the regular list of machines.
else{
MachineServices.query(page).then(function (data) {
_.each(data.results, function (machine, index, list) {
CustomerServices.get(machine.customer_id).then(function(data){
machine.CustomerData = data.results;
});
});
$scope.Machines = data.results;
$scope.pages = data.pages;
});
}
});
推荐答案
您代码中的问题是:MachineServices.getByCustomerId
和 MachineServices.query
是 异步.当你调用这些函数时,来自服务器的数据还没有到达,这些行
The problem in your code is: MachineServices.getByCustomerId
and MachineServices.query
are asynchronous. When you call these functions, data from the server does not arrive yet and these lines
$scope.Machines = data.results;
$scope.pages = data.pages;
尚未调用.
链接函数中的作用域绑定到父级的作用域.但是当调用 link
函数时,父的 scope.pages 仍然未定义(由于 asyn)
Scope in your link function is bound to the parent's scope. But when the link
function is called, the parent's scope.pages is still undefined (due to asyn)
当我们使用角度数据绑定时,我们应该被动,只需监听变化并做出相应的反应(例如使用 $watch),因为我们的代码不知道也不应该知道绑定的属性何时具有值或更新其值.让 angular 通知我们变化
When we work with angular data-binding, we should be passive, just listen for changes and react accordingly(use $watch, for example), because our code does not know and should not know when the bound property has value or has its value updated. Let angular notify us the changes
这篇关于AngularJS:指令和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!