我正在尝试学习新的组件语法。如果我在控制器中静态设置用户变量,它会起作用,我会在页面上看到数据。如果我尝试从服务中获取相同的数据,则不会显示数据。在将数据分配给 this.user 变量后,我在 then 承诺中看到了数据。
我创建了一个 plunkr 来向您展示我正在尝试的内容。
http://plnkr.co/BGXesnKBmQGUlVH33jNa
angular.module('myWebApp', ['myModule']);
angular.module('myModule', []);
angular.
module('myModule').
component('myComponent', {
controller: ['myService', function myController(mySvc) {
mySvc.getUser().then(function (data) { // This gets data but does not populate view. Why?!
this.user = {
name: 'Joe',
last: 'Shmoe'
};
console.log(user); // Populated with data from service
});
// Comment out above and uncoment this and it works!
// this.user = {
// name: 'Joe',
// last: 'Shmoe'
// };
}],
template: 'Hello, {{ $ctrl.user.name }}!',
});
angular.
module('myModule').
factory('myService', ['$timeout', function ($timeout) {
function getUser() {
// Simulate http get
return $timeout(function() {
return {
name: 'Joe',
last: 'Shmoe'
};
}, 1000);
}
return {
getUser: getUser
};
}]);