如何将“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');
});
});
答案 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;
}
});