这是 Fiddle我正在使用学习 angular js
简而言之,正在使用的 JS
文件:
angular.module('ngApp', [])
.service('myownservice', '$q', function ($timeout, $q) {
this.httpcall = function() {
var httpresp = "1818";
//making an http call over here.
return httpresp;
};
this.UpdateSomeData = function () {
var defer = $q.defer();
myownservice.httpcall().then(function(data) {
defer.resolve(data);
});
return defer.promise;
};
})
.controller('ctrl', function ($scope, myownservice) {
$scope.value = UpdateSomeData();
});
html 页面
:
<div ng-controller="ctrl">{{value}}</div>
但是我收到类似
的错误参数 'fn' 不是函数,得到字符串
。
有什么想法吗?
最佳答案
这有多个问题。
首先,您在 myownservice
中的注入(inject)没有 [
和 ]
并且没有提供 $timeout
接下来,在服务中,您需要通过 this
访问它自己,而不是给它自己命名。
接下来,您需要从 httpcall
方法返回一个 promise ,而不仅仅是数字。
它应该是这样的,
angular.module('ngApp', [])
.service('myownservice', ['$q', function($q) {
this.httpcall = function() {
var defer = $q.defer();
var httpresp = "1818";
defer.resolve(httpresp);
return defer.promise;
// replace all this with your $http call and return it..
// it returns promise itself so you wouldn't need to create on your own
};
this.UpdateSomeData = function() {
return this.httpcall();
};
}])
.controller('ctrl', function($scope, myownservice) {
myownservice.UpdateSomeData().then(function(val) {
$scope.value = val
})
});
关于javascript - 当通过 Controller 评估和发送值时,Angular $scope.value 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43393435/