Skip to content

Instantly share code, notes, and snippets.

@telagraphic
Created April 24, 2015 12:36
Show Gist options
  • Save telagraphic/fe8460bbe65ce80e3537 to your computer and use it in GitHub Desktop.
Save telagraphic/fe8460bbe65ce80e3537 to your computer and use it in GitHub Desktop.
Restangular-CRUD
angular.module('angularails.articles', [])
.service('Articles', function(Restangular) {
var articles = Restangular.all('articles');
return {
all: function() {
return articles.getList();
},
show: function(article) {
return articles.get(article);
},
update: function(article) {
return article.put();
},
create: function(newArticle) {
return articles.post(newArticle);
},
destroy: function(article) {
return article.remove();
}
};
})
.controller('ArticlesCtrl', function($scope, Articles, $stateParams, $state) {
$scope.articles = {};
$scope.newArticle = {};
Articles.all().then(function(articles) {
$scope.articles = articles;
});
$scope.postArticle = function() {
Articles.create($scope.newArticle).then(function(article) {
$scope.articles.push(article)
});
$scope.newArticle = {};
};
})
.controller('ArticleCtrl', function($scope, Articles, getArticle, $stateParams, $state) {
$scope.article = {};
$scope.editable = false;
$scope.makeEditable = function() {
$scope.editable = true;
};
Articles.show($stateParams.id).then(function(article) {
$scope.article = article;
});
$scope.updateArticle = function() {
Articles.update($scope.article).then(function(updatedArticle) {
$scope.article = updatedArticle;
});
$scope.editable = false;
};
$scope.removeArticle = function() {
Articles.destroy($scope.article).then(function(article) {
$state.go('articles');
});
};
});
<div ng-hide="editable">
<h1>{{article.title}}</h1>
</div>
<form ng-show="editable" ng-submit="updateArticle()">
<input type="text" ng-model="article.title"/>
<input type="submit" value="update"/>
</form>
<button ng-click="makeEditable()">Edit Article</button>
<button ng-click="removeArticle()">Remove Article</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment