30

我是新來的角js。我試圖從選擇的ng-change中調用工廠服務方法'getScoreData',但無法完成。請幫忙。如何從angularjs中select的ng-change調用服務方法?

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

是服務工廠方法和來自控制器的實例化。我嘗試從select的ng-change實例化,但它既沒有給出錯誤,也沒有被調用。

回答

56

你在你的代碼中的至少兩個問題:

  • ng-change="getScoreData(Score)

    角沒有看到getScoreData方法是指定義的服務

  • getScoreData: function (Score, callback)

    我們不由於GET返回承諾,因此不需要使用回調。改爲使用then

這裏是一個工作例子(I僅用於模擬隨機地址):

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

+0

適合我。 –

+0

感謝@Maxim這個。它工作順利 –