zoukankan      html  css  js  c++  java
  • angularJS $resource

    $resource是一个更方便地与RESTful服务器API进行交互,可以方便地定义一个REST资源,而不必手动所有的声明CRUD方法的Service。

    使用

    1.要使用$resource首先要在HTML中引入它的独立的js文件;

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-resource.js"></script>

    2.在app中添加对应的依赖注入;

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

    3.为资源建立一个factory;

    app.factory('Notes',['$resource', function(){
        return $resource('/notes/:id');
    }]);

    注:当然,你也可以不把$esource的实例放到Factory里,直接在控制器中存起来:var Notes = $resource('/notes/:id)

    4.进行增删改查(CRUD)的操作

    app.controller('NotesCtrl',['$scope','Notes',function(){
        var notes = Notes.query(function(){
            //GET or POST code
        });
        
        var note = new Notes({content:'xxx'});
    }]);

    $resource提供了五种默认操作:get, query, save, remove, delete。你可以配置一个update操作来完成HTTP PUT。

    app.factory('Notes', ['$resource', function($resource){
        return $resource('/notes/:id', null, {
            update:{method:'PUT'}
        });
    }]);

    在创建控制器时引入ngResource

    var helloApp = angular.module("helloApp", [ 'ngResource' ]);
    helloApp.controller("HttpController", [ '$scope', '$resource', function($scope, $resource) {
        //code
    } ]);

    用POST方法来提交表单信息

    var helloApp = angular.module("helloApp", [ 'ngResource' ]);
    helloApp.controller("HttpController", [ '$scope', '$resource', function($scope, $resource) {
        $scope.users = [
            { 
                'firstname': 'Ajitesh',
                'lastname': 'Shukla',
                'address': 'Hyderbad',
                'email': 'ajitesh101@gmail.com'
            },
            {
                'firstname':'Sumit',
                'lastname':'Jha',
                'address':'Muzaffarpur',
                'email':'sumitjha2011@yahoo.com'
            },                                                                        
        ];
     
        $scope.saveUser = function(){                            
            // 创建一个resource对象
            var User = $resource('/user/new');
            
            // 调用save方法
            //(其实和我们$http.post(url,data).success(function(){})是一样的,只是它封装一下而已)
            User.save(
                {
                    firstname:$scope.firstname,
                    lastname:$scope.lastname,
                    address:$scope.address,
                    email:$scope.email
                }, 
                function(response){
                    $scope.message = response.message;
                }
            );
        };
    }]);
  • 相关阅读:
    python3 与dict相关的魔法方法。使用于二叉搜索树的类中
    笔记:nestjs学习基础(1)
    ES6 --(10)class使用、class继承
    redux --(1)核心概念(stateaction educer)、三大原则、todolist with redux
    antV--G2 学习
    react源代码重点难点分析
    jQuery-ui源代码重点难点分析
    webuploader上传插件源代码重点难点分析
    破解jQuery Deferred()异步执行的神秘世界
    ueditor源代码重点难点分析
  • 原文地址:https://www.cnblogs.com/zcynine/p/5179456.html
Copyright © 2011-2022 走看看