我是新的角j。我试图调用工厂服务方法’getscoreData’从ng的变化,但不能够得到它完成。请帮忙。
<select ng-model="score" ng-change="getscoreData(score)" ng-options="c.name for c in scores"></select>
Angularjs代码:
var app = angular.module('audiapp',[]); app.controller('audiLayoutCtrl',function ($scope,scoreDataService) { scoreDataService.getscoreData($scope.score,function (data) { $scope.scoreData = data; }); }); app.factory('scoreDataService',function ($http) { return { getscoreData: function (score,callback) { var params = { questionCode: score.code } return $http({ url: 'Home/GetAvgData',method: 'GET',params: params }).success(callback); } }; });
您的代码至少有两个问题:
> ng-change =“getscoreData(score)
Angular没有看到getscoreData方法引用定义的服务
> getscoreData:function(score,callback)
我们不需要使用回调,因为GET返回promise。然后改用。
这里是一个工作示例(我使用随机地址仅用于模拟):
HTML
<select ng-model="score" ng-change="getscoreData(score)" ng-options="score as score.name for score in scores"></select> <pre>{{scoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule',['ngResource']); fessmodule.controller('fessCntrl',function($scope,scoreDataService) { $scope.scores = [{ name: 'Bukit Batok Street 1',URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore,SG,Singapore,153 Bukit Batok Street 1&sensor=true' },{ name: 'London 8',London 8&sensor=true' }]; $scope.getscoreData = function(score) { scoreDataService.getscoreData(score).then(function(result) { $scope.scoreData = result; },function(result) { alert("Error: No data returned"); }); }; }); fessmodule.$inject = ['$scope','scoreDataService']; fessmodule.factory('scoreDataService',['$http','$q',function($http) { var factory = { getscoreData: function(score) { console.log(score); var data = $http({ method: 'GET',url: score.URL }); return data; } } return factory; }]);
演示Fiddle