Best practice of RestAngular

你说的曾经没有我的故事 提交于 2019-12-03 16:06:37
Poyraz Yilmaz

First of all do not use service logic on the controller, instead use angular services for this purpose.

Let me share you how I build my projects,

First build Restangular Service :

angular.module('example').factory('exampleService', ['Restangular', function(Restangular){

    // this is service object with list of methods in it
    // this object will be used by controller
    var service = {
        getExamples: getExamples,
        getExample: getExample
    };

    // get examples from server by using Restangular
    function getExamples(){
        return Restangular.all('examples').getList();
    }

    // get example with given id from server by using Restangular
    function getExample(exampleId){
        return Restangular.one('examples', exampleId).get();
    }

    return service;

}]);

here we build exampleService now let's inject it into a controller

angular.controller('ExampleCtrl', ['exampleService', function(exampleService){

    // get examples by using exampleService
    exampleService.getExamples().then(function (examples) {
        $scope.examples = examples;
    });

    // get example with given id by using exampleService
    exampleService.getExample('1234').then(function (example) {
        $scope.example = example;
    });

}]);

This is how I use it basically. For more advanced usage you can look the examples in Restangular Github Page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!