我希望会有一个“ Hello World!” 在的输出中ctrl.hellos
,但我什么也没得到。
<div ng-app="myApp">
<div ng-controller="MyCtrl as ctrl" ng-bind="ctrl.hellos"></div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.provider('helloWorld', function() {
var _name = 'Default';
this.$get = function($q) {
return {
sayHello: function() {
var deferred = $q.defer()
setTimeout(function() {
if (_name !== 'Default') {
deferred.resolve('Hello, ' + _name + '!');
} else {
deferred.reject('No changes');
}
}, 3000);
return deferred.promise;
}
}
};
this.setName = function(newName) {
_name = newName;
}
});
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
myApp.controller('MyCtrl',['helloWorld',myCtrl]);
function myCtrl(helloWorld) {
helloWorld.sayHello().then(function(text){
this.hellos = text
},function(msg){
this.hellos = msg
})
}
</script>
代码中有什么错误吗?
您所遇到的问题在Promises / A +规范中定义。
主要在这里:
onFulfilled和onRejected必须作为函数调用(即没有此值)。
由于promise的promise形式符合该标准,因此您onFulfilled
已将window
对象设置为上下文,类似于setTimeout
/ setInterval
etc。
您有两种选择。
别名this
,.bind
您的回调函数或使用将应用调用上下文的ES2015箭头函数。(与使用类似的结果.bind
)
// alias
var self = this;
helloWorld.sayHello().then(function(text){
self.hellos = text
},function(msg){
self.hellos = msg
});
// bind
helloWorld.sayHello().then(function(text){
this.hellos = text
}.bind(this),function(msg){
this.hellos = msg
}.bind(this));
// Arrow function
helloWorld.sayHello().then((text) => {
this.hellos = text
},(msg) => {
this.hellos = msg
});
仅供参考 ngBind
通常,您不会直接使用ngBind,而是会使用类似{{expression}}的双重卷曲标记,它虽然相似,但比较冗长。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句