在指令和服务器上同步服务中的数据

时间:2015-02-06 08:11:28

标签: angularjs angularjs-directive angularjs-scope

我有以下

服务

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'
    }
}

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

由于

1 个答案:

答案 0 :(得分: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