在AngularJS中干

时间:2015-10-18 07:02:34

标签: javascript angularjs

我有8个控制器使用12个常用功能。但3-4个功能各不相同。我怎么能不重复自己的每一个?我正在使用每个控制器共用的服务。我的代码:

app.controller("ArticleController",['$scope','$http','dataService',function($scope,$http,dataService){

$scope.comments={};
$scope.articles = {articles:[]};
$scope.reachedEnd = false;
$scope.getArticles //implemented differently for each of the controllers
//Here it is used to fetch latest articles
/* common 12 functions 
   to deal with dom events. On addition of new comments, upvotes, etc
*/
function getArticlesSuccess(articles){
    articles.articles.forEach(function(article){
        $scope.articles.articles.push(article);
    });
    $scope.reachedEnd = articles.reachedEnd;
}

$scope.addToReadingList = function(id,userid){
    dataService.addToReadingList(id,userid);
};

$scope.removeFromReadingList = function(id,userid){
    dataService.removeFromReadingList(id,userid);
};

$scope.upvote = function(id,userid){
    upvoteIncrementer(id,userid);
    dataService.upvote(id);
};

$scope.deleteComment = function(commentId){
    dataService.deleteComment(commentId);
};

var upvoteIncrementer = function(id,userid){
    console.log(id);
    $scope.articles.articles.forEach(function(article){
        console.log(article);
        if(article && article._id === id && !article.votes.set){
            if(article.votes.down.indexOf(userid)>-1){
                article.votes.down.splice(article.votes.down.indexOf(userid));
                console.log('removed vote');
            }
            article.votes.up.push(userid);
            article.votes.set = true;
        }
    });
}


$scope.downvote = function(id,userid){
    downvoteIncrementer(id,userid);
    dataService.downvote(id);
}

var downvoteIncrementer = function(id,userid){
    console.log(id);
    $scope.articles.articles.forEach(function(article){
        console.log(article);
        if(article && article._id === id && !article.votes.set){
            console.log(article);
            if(userid in article.votes.up){
                article.votes.up.splice(article.votes.up.indexOf(userid));
                console.log('removed vote');
            }
            article.votes.down.push(userid);
            article.votes.set = true;
        }
    });
}


$scope.showComments = function(id){
    dataService.getComments(id).then(function(data){
        $scope.articles.articles.forEach(function(article){
            if(article._id === id ){
                article.fetchedComments = data.comments;
            }
        });
        console.log($scope.fetchedComments);
    });
}

$scope.commentForm = function(id,user,contents) {
    dataService.postComments(id,user,contents).then(function(x){
    $scope.articles.articles.forEach(function(article){
            if(article._id === id ){
                article.fetchedComments.push(x);
                console.log(article.fetchedComments);
            }
        });
    });
}
}]);

另一个控制器的代码:

app.controller("ArticleController",['$scope','$http','dataService',function($scope,$http,dataService){
$scope.comments={};
$scope.articles = {articles:[]};
$scope.reachedEnd = false;
$scope.getArticles //implemented differently for each of the controllers
//Here it is used to fetch top articles by the day
/* common 12 functions */
}]);

编辑:添加了dataservice.js

(function(){

angular.module('newstalk')
    .factory('dataService',['$http','$q',dataService]);

function dataService($http,$q){
    return {
        getArticles : getArticles,
        postComments : postComments,
        addToReadingList : addToReadingList,
        getReadingList : getReadingList,
        upvote : upvote,
        downvote : downvote,
        getComments : getComments,
        removeFromReadingList : removeFromReadingList,
        deleteComment : deleteComment
    };

    function getArticles(numsRecieved){
        return $http({
            method:'get',
            url:'/api/articles/'+parseInt(numsRecieved/10)
        })
        .then(sendResponse);
    }

    function deleteComment(commentId){
        $http.delete('/api/delete/comment/'+commentId)
            .then(function(response){console.log(response);});
    }

    function sendResponse(response){
            return response.data;
    }

    function sendResponseComments(response){
            return response.data;
    }

    function postComments(id,user,contents){
        var uid = user._id;
        var uname=user.name;
        var c =  contents;
        var data = {
            content: c,
            id: uid,
            name:uname
        };
        console.log(data);
        return $http.post('/api/article/'+id,data).then(sendResponse);
    }
    function addToReadingList(id,userid){
        var data = {
            id: id,
            user: userid
        };
        $http.post('/api/user/add/'+userid,data);   
    }

    function removeFromReadingList(id,userid){
        var data = {
            id: id,
            user: userid
        };
        $http.post('/api/user/rem/'+userid,data);   
    }

    function getReadingList(userid){
        console.log('/api/readinglist/0');
        return $http({
            method:'get',
            url:'/api/readinglist/0'
        })
        .then(sendResponse);
    }           
    function upvote(id){
        return $http({
            method:'post',
            url:'/api/article/up/'+id
        });
    }
    function downvote(id){
        return $http({
            method:'post',
            url:'/api/article/down/'+id
        });
    }
    function getComments(id){
        return $http({
            method:'get',
            url:'/api/article/comments/'+id
        })
        .then(sendResponseComments);
    }

}
})()

请建议一种方法,以便我可以减少代码,只需要在一个区域进行更改即可在任何地方生效。

1 个答案:

答案 0 :(得分:2)

您可以将一个函数用作服务,并使该函数返回一个对象,该对象具有您需要在控制器之间重用的函数。您可以在每个控制器中调用该函数,传递参数以根据您正在使用的控制器配置函数。

app.factory('myStuff', function($http) {
  return function(urlForController) {
    return {
      foo: function() {
        // use the parameters in your functions
        return $http.get(urlForController);
      },
      bar: //etc
    };
  };
});

app.controller('myCtrl', function($scope, myStuff) {
  // call the service function, passing in the controller specific parameters to configure the returned object
  $scope.myStuff = myStuff('/whatever');
});

您甚至可以将控制器的$scope传递给服务,并让这些功能操纵您所需的功能。

$scope.myStuff = mystuff($scope, '/whatever');

// the service:
return function(scope, urlForController) {