AngularJs 抓狂之: $q promise 自动unwarp功能被禁用了
昨天剛知道,原來(lái)把一個(gè)Promise綁定到Scope,View會(huì)自動(dòng)顯示該P(yáng)romise的值(auto-unwarp),但是晚上回家試的時(shí)候發(fā)現(xiàn),無(wú)論如何都不行。又浪費(fèi)了兩個(gè)多小時(shí)找原因,最后才發(fā)現(xiàn),這個(gè)auto-unwrap的功能在AngularJs 1.2.0的某個(gè)RC之后就被禁用了。官方用詞Deprecated,沒(méi)有替代怎么叫deprecated呢?明明就是removed!
這是StackOverflow的提問(wèn):http://stackoverflow.com/questions/21193400/why-promise-in-factory-not-working-since-angularjs-1-2-0
這是Plnkr:?http://plnkr.co/edit/w2O8Ci?p=preview
所以,下面代碼里面的Promise已經(jīng)不會(huì)自動(dòng)綁定了,要讓他工作正常,需要:
NameFactory.getName().then(function(data){$scope.name = data});代碼: <!DOCTYPE html> <html ng-app="myApp"><head><!--<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>--><script src="http://code.angularjs.org/1.2.9/angular.min.js"></script><script>var app = angular.module('myApp', []);app.factory('NameFactory', function($http, $q) {return {getName: function() {var deferred = $q.defer();deferred.resolve({name: "World"});return deferred.promise;}}});app.controller("NameCtrl", function($scope, NameFactory) {$scope.name = NameFactory.getName();});</script> </head><body ng-controller="NameCtrl"><h1>Hello, {{name.name}}</h1> </body></html>
所以正確的做法是:
<!DOCTYPE html> <html ng-app="myApp"><head><script src="http://code.angularjs.org/1.2.9/angular.min.js"></script><script>var app = angular.module('myApp', []);app.factory('NameFactory', function($http, $q) {return {getName: function() {var deferred = $q.defer();deferred.resolve({name: "World"});return deferred.promise;}}});app.controller("NameCtrl", function($scope, NameFactory) {NameFactory.getName().then(function(data){$scope.name = data;});});</script> </head><body ng-controller="NameCtrl"><h1>Hello, {{name.name}}</h1> </body></html>轉(zhuǎn)載于:https://www.cnblogs.com/puncha/p/3876855.html
總結(jié)
以上是生活随笔為你收集整理的AngularJs 抓狂之: $q promise 自动unwarp功能被禁用了的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Matlab--sort排序
- 下一篇: POJ 2253 Frogger(最短路