如何在Angular控制器中添加REST“show”?

时间:2015-04-24 14:32:55

标签: angularjs

如何将“api / things /:id”等路由的功能添加到以下CRUD AngularJS控制器?

angular.module('maybeApp')
.controller('MainCtrl', function ($scope, $http, socket) {
$scope.awesomeThings = [];

$http.get('/api/things').success(function(awesomeThings) {
  $scope.awesomeThings = awesomeThings;
  socket.syncUpdates('thing', $scope.awesomeThings);
});

$scope.addThing = function() {
  if($scope.newThing === '') {
    return;
  }
  $http.post('/api/things', { name: $scope.newThing });
  $scope.newThing = '';
};

$scope.deleteThing = function(thing) {
  $http.delete('/api/things/' + thing._id);
};

$scope.$on('$destroy', function () {
  socket.unsyncUpdates('thing');
});
});

2 个答案:

答案 0 :(得分:2)

您可以创建工厂。例如:

var app = angular.module('myApp', []);

app.factory('thingsFactory', function($http) {
    var baseAddress = // address you need;
    var url;
    return {
        getAll: function() {
            url = baseAddress;
            return $http.get(url);
        },
        postThing: function(item) {
            url = baseAddress;
            return $http.post(url, item);
        },
        deleteThing: function(id) {
            url = baseAddress + id;
            return $http.delete(url);
        },
        .......
    }
}

然后将thingsFactory注入controller并使用。例如:

thingsFactory.deleteThing('id_that_you_need').success(function (result) {
     // if the server respond
     alert('Thing has been deleted');
}).error(function () {
     alert('Error.... Please blah-blah-blah... :) ');    
});

答案 1 :(得分:0)

我建议您使用ngResource并且不要直接在controller上使用它,它不应该是controller的责任,而是使用service代替将该服务注入您的controller

angular.module('myApp'),['ngResource'])
.factory('myService', function(){
 var myService = $resource('/serviceUrl', {}, {
      get: {
        method: 'GET',
        responseType: 'json'
      },
      delete: {//...
      }
    });
    return {
    getSomething: function(){
      return myService.get().$promise;
    };    
})

.controller('MyController', function($scope, myService){
  myService.getSomething()
  .then(function(data){
    $scope.myData = data;
  }
});