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;
                }
            );
        };
    }]);
  • 相关阅读:
    socketpair和pipe的区别
    C++异常与析构函数及构造函数
    System v shm的key
    不可靠信号SIGCHLD丢失的问题
    非阻塞IO函数
    Android 编译时出现r cannot be resolved to a variable
    找工作笔试面试那些事儿(5)---构造函数、析构函数和赋值函数
    unable to load default svn client 和 Eclipse SVN 插件与TortoiseSVN对应关系
    演示百度地图操作功能
    求第i个小的元素 时间复杂度O(n)
  • 原文地址:https://www.cnblogs.com/zcynine/p/5179456.html
Copyright © 2011-2022 走看看