gpt4 book ai didi

angularjs - 如何从AngularJS中选择的ng-change调用服务方法?

转载 作者:行者123 更新时间:2023-12-02 19:52:21 24 4
gpt4 key购买 nike

我是 Angular JS 新手。我试图从 select 的 ng-change 调用工厂服务方法“getScoreData”,但无法完成它。请帮忙。

HTML 代码:

<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);
}
};
});

上面是服务工厂方法及其从 Controller 实例化。我尝试从 select 的 ng-change 实例化,但它既没有给出错误,也没有被调用。

最佳答案

您的代码中至少存在两个问题:

  • ng-change="getScoreData(分数)

    Angular 没有看到引用已定义服务的 getScoreData 方法

  • getScoreData:函数(分数、回调)

    我们不需要使用回调,因为GET返回promise。请改用 then

这是一个工作示例(我仅使用随机地址进行模拟):

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',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 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

关于angularjs - 如何从AngularJS中选择的ng-change调用服务方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20674220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com