AngularJS动态获取和对象

时间:2013-12-30 10:07:37

标签: angularjs

我在我的一个控制器中有这个(注意id):

Post.get
        id: "2"

        # Success
      , (response) ->
        $scope.post = response

        # Error
      , (response) ->

但我想做的是如何动态获取特定帖子,即{{getPost("2")}}

对不起,如果我问的是非常明显的,但我是初学者,并且已经坚持了几个小时。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:1)

最好将服务器请求分成工厂,例如让我们调用你的工厂jonFactory和你的应用程序jonApp,所以现在我们有了包含我们所有工厂/服务的services.js文件。

angular.module('jonApp',[]).
    factory('jonFactory', function($http) {
        function.getPost = function(id) {
            var url = "your url for post";
            var args = { 'id': id };
            $http.post(url, args)
                .success(function(data){
                    return data;
                });
        }
    });

希望我理解你的权利

你的Ctrl应该使用你的工厂,所以你必须通过以下方式包含它:

angular.module('jonApp.controllers', []).
    controller('JonController', function($scope, jonFactory) {
        $scope.getPostById = function(id) {
            return jonFactory.getPost(id);
        }
});

并在视图中显示功能结果:

 <div>{{getPostById(2)}}</div>