0

次のサービスがあります。

angular.module('adminApp')
.factory('subjectService', function ($http) {
    return {
        get: function (testAccountId) {
            return $http({
                method: 'GET',
                url: '/api/Subjects/GetSelect',
                params: { testAccountId: testAccountId }
            });
        }
    }
});

次のコードは、http を直接呼び出すと機能しますが、サービスを使用すると機能します。

    $scope.$watch('selectedTestAccount', function () {
        if ($scope.selectedTestAccount != null) {
            $scope.myData = null;

            $http({
                method: 'GET',
                url: '/api/Subjects/GetSelect',
                params: { testAccountId: $scope.selectedTestAccount }
            }).success(function (result) {
                $scope.subjects = result;
                $scope.myData = null;
            });

            //subjectService.get($scope.selectedTestAccount)
            //    .then(function (result) {
            //        $scope.subjects = result;
            //        $scope.myData = null;
            //        alert($scope.subjects);
            //    }, function (result) {
            //        alert("Error: No data returned");
            //    });
        }
    });

この質問に関連しています。これはサービスを呼び出す正しい方法ですか。次のような別の提案があり、promise を使用していました。私はこれを行うべきですか:

services.factory('MultiRecipeLoader', ['Recipe', '$q',
   function(Recipe, $q) {
      return function() {
         var delay = $q.defer();
         Recipe.query(function(recipes) {
            delay.resolve(recipes);
         }, function() {
            delay.reject('Unable to fetch recipes');
         });
         return delay.promise;
      };
}]);
4

1 に答える 1

0

あなたの例をプランカーで再現しようとしました。それがあなたが探しているものかどうか教えてください:

http://plnkr.co/edit/6s5utccjgHTnrrokM1u8?p=preview

このデモには、コントローラーで$watchedであるアカウント変数の値を変更するドロップダウンがあります。アカウントの値が変更されると、SubjectsServices が呼び出され、サブジェクトの名前で順序付けられていないリストが更新されます。さらに、同じ値が入力されたドロップダウンもあります。

値を変更する唯一の方法がドロップダウンを使用する場合、選択でng-changeディレクティブを使用して、同じ作業を行う更新関数を呼び出すことしかできない可能性があります。

$scope.update = function() {
    SubjectService.get($scope.account).then(function(result) {
        $scope.subjects = result.data;
    }, function(result) {
        // error handling...
    }); 
};

<select ng-change="update()"></select>

$http promiseでメソッドからパラメータで受け取ったオブジェクトには、要求されたデータを含む data プロパティがあります。

$http.get(...).then(function(result) {
    var subjects = result.data;
});
于 2013-04-15T04:52:32.220 に答える