how to call service method from ng-change of select in angularjs?

Samir Shah picture Samir Shah · Dec 19, 2013 · Viewed 112.3k times · Source

I am new to angular js. I am trying to call factory service method 'getScoreData' from ng-change of select, but not able to get it done. please help.

Html code:

<select ng-model="Score" ng-change="getScoreData(Score)" ng-options="c.name for c in     Scores"></select>

Angularjs code:

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

above is the service factory method and its instantiate from controller. I tried instantiating from ng-change of select but its neither giving error nor its getting called.

Answer

Maxim Shoustin picture Maxim Shoustin · Dec 19, 2013

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

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

Demo Fiddle