AngularJS将服务变量绑定到控制器

时间:2014-07-15 04:22:14

标签: angularjs data-binding service binding

我是一个Angular noob,并且在将一个变量从我的某个服务绑定到我的一个控制器时出现问题。我已经阅读了至少十几篇关于这个主题的帖子,似乎没有什么对我有用。

这是控制器:

app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
    $scope.teamService = teamService;
    $scope.selectedTeam = null;



    $scope.selectTeam = function(teamId){
        $scope.selectedTeam = teamService.getTeam(teamId, $scope.login.loginId);
    };

}]);

这是服务:

angular.module('teamService', [])
.service('teamService', function($http, $q){
    this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
    this.userTeams = [];

    this.getTeam = function(teamId, loginId) {
        var postData = {teamId: teamId, loginId: loginId};
        var promise = $http({
            url: "/url-for-getting-team",
            method: "POST",
            data: postData
        });
        promise.success(function (data) {
            if (data.status === "success") {
                this.selectedTeam = data.response;
                return data.response;
            }
        });
        promise.error(function () { //TODO handle getTeam errors
            return {};
        });
    };


    this.getSelectedTeam = function(){
      return this.selectedTeam;
    };

 });

这是模板:

<div class="jumbotron main-jumbo" ng-controller="TeamController">
    <h1>{{selectedTeam.teamName}}</h1>
</div>

我尝试绑定到getSelectedTeam函数和服务变量本身。我是否需要在控制器中设置$ watch功能?非常感谢任何帮助。

编辑:

我尝试将我的服务转变为工厂,这仍然没有帮助我,所以我看了一个正在工作的提供程序,我已经在应用程序中编写了。我将“teamService”转换为提供者,最终像魅力一样工作。谢谢你的贡献。

来自我的新提供商的代码:

angular.module('teamService', [])
.provider('teamService', function () {
    var errorState = 'error',
        logoutState = 'home';

    this.$get = function ($rootScope, $http, $q, $state) {

        /**
         * Low-level, private functions.
         */


        /**
         * High level, public methods
         */
        var wrappedService = {
            /**
             * Public properties
             */
            selectedTeam: {teamName:"Select a team"},
            userTeams : null,
            createTeam: function(loginId, name, description, locationName, managed){
                var postData = {loginId:loginId, teamName:name, teamDescription:description, teamLocationName:locationName, teamManaged:managed};
                var promise = $http({
                    url: "/create-team-url",
                    method: "POST",
                    data: postData
                });

                return promise;
            },

            getTeam: function(teamId, loginId) {
                var postData = {teamId: teamId, loginId: loginId};
                var promise = $http({
                    url: "/get-team-url",
                    method: "POST",
                    data: postData
                });

                promise.success(function (data) {
                    if (data.status === "success") {
                        wrappedService.selectedTeam = data.response;
                    }
                });
                promise.error(function () { //TODO handle getTeam errors
                    wrappedService.selectedTeam = {};
                });
            },

            getUserTeams:  function(loginId) {
                var postData = {loginId: loginId};
                var promise = $http({
                    url: "/team-list-url",
                    method: "POST",
                    data: postData
                });
                return promise;
            },

            joinTeam:  function(teamId, loginId){
                var postData = {teamId:teamId, loginId:loginId};
                var promise =$http({
                    url: "/join-team-url",
                    method: "POST",
                    data: postData
                });
                return promise;
            },

            getSelectedTeam: function(){
                return wrappedService.selectedTeam;
            }
        };

        return wrappedService;
    };
});

2 个答案:

答案 0 :(得分:1)

正如我的编辑中所见。我将我的服务转换为提供程序,所有更改似乎都传播到视图而没有任何问题。我需要进一步分析工厂,服务和提供商之间的差异,以便更好地了解这里发生的事情。

答案 1 :(得分:0)

代码的主要问题是使用promises的方式。您可以在服务中更正它,也可以在控制器中处理它。作为后者的一个例子,你可以重写上面的内容:

控制器代码:

app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
    $scope.teamService = teamService;
    $scope.selectedTeam = null;

    $scope.selectTeam = function(teamId){
        teamService.getTeam(teamId, $scope.login.loginId).then(
            function(result){
                $scope.selectedTeam = result.data;
            },
            function(error){
                console.log(error);
            }
        )
    };

}]);

服务代码:

angular.module('teamService', [])
.service('teamService', function($http, $q){
    this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
    this.userTeams = [];

    this.getTeam = function(teamId, loginId) {
        var postData = {teamId: teamId, loginId: loginId};
        return $http({
            url: "/url-for-getting-team",
            method: "POST",
            data: postData
        });
    };


    this.getSelectedTeam = function(){
      return this.selectedTeam;
    };

 });

您也可以在服务本身处理此问题,但需要更多代码。关键是getTeam调用是异步的,需要使用适当的promise构造来处理。