2015-02-06 37 views
0

服务我有以下同步数据从在指令和关于服务器

服务

angular.module('app') 
    .factory('UserFactory', function ($http) { 
    function profile() { 
     return $http.get('/gimme') 
     .then(function success (response) { 
      return response; 
     }); 
    };  
    var user = { 
     profile: profile 
    }; 


    return user; 

它是在一个控制器中使用,如下所示:

控制器

angular.module('app') 
    .controller('HeaderCtrl', function ($scope, UserFactory) { 
    $scope.awesomeThings = [ 
     'HTML5 Boilerplate', 
     'AngularJS', 
     'Karma' 
    ]; 
    $scope.user = UserFactory.profile().then(function (response) { 
     $scope.user = response.data; 
    }); 

    $scope.change = function() { 
     $scope.user.name = 'New Name' 
    } 
} 

如果我在使用HeaderCtrl的指令中调用change()方法,确保临时更改user.name的更改实际上在我的服务器上更改它的最佳方法是什么?换句话说,我将如何触发put请求(我假设需要在Factory上调用某个函数,但我不确定是否确保调用该函数或将函数调用放在控制器中的最佳方式) 。

感谢

+1

在您的服务中为'$ http.put()'添加函数,并用'user'调用它。和btw松散assigment'$ scope.user = UserFactotory.profile()...'并且在promise已经解决之后就离开它。 – 2015-02-06 09:01:53

+0

有帮助吗,不是吗? – 2015-02-08 20:31:41

回答

0

这里的延长你提供,使用免费JSONPlaceholder API代码的例子。我认为例子本身就足够了答案?

HTML

<body ng-controller="Ctrl as vm"> 
    <div>data: {{ vm.todo | json }}</div> 
    <div>response: {{ vm.response | json }} </div> 
    <hr> 
    <button type="button" ng-click="vm.change('my new title')">Change title</button> 
</body> 

的JavaScript

app.controller('Ctrl', function(TodoService) { 
    var vm = this; 
    var id = 1; 

    TodoService.getPost(id).then(function(response) { // Get 
    vm.todo = response.data; 
    }); 

    vm.change = function(val) { 
    vm.todo.title = val; 

    TodoService.putPost(vm.todo).then(function(response) { // Put 
     vm.response = response.status + ' ' + response.statusText; 
    }).catch(function(error) { 
     vm.response = angular.toJson(error); 
    }); 
    }; 
}); 

app.factory('TodoService', function($http) { 
    var endpoint = 'http://jsonplaceholder.typicode.com/todos/'; 
    var todoService = {}; 

    todoService.getPost = function(id) { 
    return $http.get(endpoint + id).then(function(response) { 
     return response; 
    }); 
    }; 

    todoService.putPost = function(todo) { 
    return $http.put(endpoint + todo.id, todo).then(function(response) { 
     return response; 
    }); 
    }; 

    return todoService; 
}); 

imgur

这里

相关plunker http://plnkr.co/edit/VBvVen

相关问题