在 AngularJS 中创建一个 JSONP API &使用 jQuery 消费 [英] Create a JSONP API in AngularJS & consume with jQuery

查看:21
本文介绍了在 AngularJS 中创建一个 JSONP API &使用 jQuery 消费的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我已经用 JQuery 创建了一个 JS API,但我想知道它是否可以用 AngularJs 来完成.

例如,想象一个像下面这样的小 API:

var $myapi= $myapi||{};;(函数($,窗口,文档,未定义){_call_myapi_jsonp:函数(参数,控制器,动作,事件名称){if (!params) params = {};var url = this.urls.base+"/"+controller+"/"+action+"?callback=?";如果(参数.回调)url = this.urls.base+"/"+controller+"/"+action+"?callback="+params.callback;url = url + "&_"+new Date();删除 params.callback;$.ajax({网址:网址,数据:参数,跨域:真,数据类型:'jsonp',缓存:假,ajaxOptions: {cache: false},jsonp: params.callback?false:true,成功:功能(数据,状态){if (eventName && eventName!=""){$($myapi).trigger(eventName,data);}}});},等级: {列表:函数(参数){参数 = 参数 ||{};params.max = params.max!=undefined?parseInt(params.max):$myapi.defaults.levels.max;params.page = params.page!=undefined?parseInt(params.page):$myapi.defaults.levels.page;params.showActives = params.showActives!=undefined?params.showActives:$myapi.defaults.levels.showActives;$myapi._call_myapi_jsonp(params,"level","listJSONP","myapi.level.list");},信息:功能(参数){$myapi._call_myapi_jsonp(params,"level","showJSONP","myapi.level.info");}}}

我一直在搜索 AngularJs 文档并在 Google 中搜索,但我还没有找到可以在 AngularJS 中制作 Jquery 代码的方法.我想也许使用 $routeProvider 可以完成,但我没有找到任何关于如何使用 $routeProvider 进行 jsonp 调用而不显示模板或重定向到某个地方的示例或文档.

解决方案

听起来你需要的是一项服务,类似于这里正在做的事情:

从服务器获取数据的推荐方式

http://jsfiddle.net/wpPhY/

但包含$resource:

http://docs.angularjs.org/api/ngResource.$resource

以下是查询 Twitter 的 JSONP 服务的基本示例(取自 http://egghead.io):

JSFiddle 演示: http://jsfiddle.net/gavinfoley/DJ6da/

angular.module('Twitter', ['ngResource']);angular.module('推特').controller('TwitterCtrl', ['$scope', '$resource', function ($scope, $resource) {$scope.twitter = $resource('http://search.twitter.com/:action',{action:'search.json', q:'angularjs', callback:'JSON_CALLBACK'},{get:{method:'JSONP'}});$scope.doSearch = 函数 () {$scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm});};}]);

此外,将 Breeze 与 Angular 结合使用也值得一看.我自己没有使用过它,但你可以用它创建一些非常酷的 CRUD 应用程序:

http://www.breezejs.com/samples/todo-angular

但是,如果您希望通过 jQuery 访问在特定 Angular 控制器(或范围)内定义的函数或属性,请查看下面的 Plnkr 和代码.

老实说,如果可能的话,我真的不会走这条路.最好从您的解决方案中完全删除 jQuery 并坚持使用 Angular.意思是编写您的 Angular API 或服务并使用 Angular 控制器/指令等使用它.

换句话说,如果您打算在您的应用程序中使用 Angular,那么请选择所有 Angular".不要尝试与 jQuery 混合搭配.它只会减慢您的速度并使您的代码更难维护.

完整的 Plnkr 演示: http://plnkr.co/编辑/X5SfKD?p=预览

HTML

<html data-ng-app="myApp"><头><link rel="stylesheet" href="style.css"><script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script><script src="myApp.js"></script><script src="script.js"></script><身体><div id="parent" data-ng-controller="ParentCtrl"><span id="someSpan">这是{{name}}.</span><div id="child" data-ng-controller="ChildCtrl">这是{{name}}.</div>获取最新推文:<input type="text" data-ng-model="twitterUser"/><button data-ng-click="getLatestAngularTwitterPost()">获取推文</button><br/><br/>最新的 {{searchTerm}} 推特帖子:<div><img id="twitterProfileImage" data-ng-src="{{profileImage}}"/><span data-ng-bind-html-unsafe="tweet" id="tweet"></span>

</html>

Angular 应用 - myApp.js

angular.module('myApp', []);angular.module('myApp').controller('ParentCtrl', function ($scope, $http) {$scope.name = "父";$scope.testFunc = 函数 () {返回测试正在运行."};$scope.twitterUser = "AngularJS";$scope.tweet;$scope.profileImage;$scope.searchTerm;//从 AngularJS 返回 Twitter 上的最新帖子$scope.getLatestAngularTwitterPost = 函数(callbackFunc){$scope.searchTerm = $scope.twitterUser;var url = "http://api.twitter.com/1/users/show.json";$http.jsonp(url, {参数:{回调:'JSON_CALLBACK',屏幕名称:$scope.twitterUser}}).成功(功能(数据){如果(回调函数){console.log("将推特结果传给回调:" + callbackFunc.name);返回 callbackFunc(data);}$scope.tweet = data.status.text;$scope.profileImage = data.profile_image_url;}).错误(功能(){$scope.tweet = "<strong>错误:无法向 Twitter 发出 JSONP 请求.</strong>";});};});angular.module('myApp').controller('ChildCtrl', function ($scope) {$scope.name = "孩子";});

jQuery - script.js

//例如.如何调用方法和更新属性//在 Angular 控制器中,来自 jQuery$(函数(){//获取 Angular 控制器ParentCtrl".//也可以使用 $('#someSpan').scope();获取ParentCntl"范围var $scopeParentCtrl = $('#parent').scope();//获取 Angular 控制器ChildCtrl".var $scopeChildCtrl = $('#child').scope();//更新 Angular 控制器ParentCtrl"中的name"属性$scopeParentCtrl.$apply(function(){$scopeParentCtrl.name = "乔";console.log("父名称改为" + $scopeParentCtrl.name);});//更新 Angular 控制器ChildCtrl"中的name"属性$scopeChildCtrl.$apply(function(){$scopeChildCtrl.name = "加文";console.log("子名称改为"+ $scopeChildCtrl.name);});//在 Angular 控制器ParentCtrl"中调用testFunc"函数console.log($scopeParentCtrl.testFunc());//在 Angular 控制器ParentCtrl"中调用 JSONP 函数$scopeParentCtrl.getLatestAngularTwitterPost(jsonpCallback);});函数 jsonpCallback(数据){var $scopeParentCtrl = $('#parent').scope();$scopeParentCtrl.tweet = data.status.text;$scopeParentCtrl.profileImage = data.profile_image_url;}

Right now I've created a JS API with JQuery, but I'm wondering if it could be done with AngularJs.

For example, Imagine a small API like the following:

var $myapi= $myapi|| {};
;(function($, window, document, undefined){
    _call_myapi_jsonp: function(params,controller,action,eventName){
    if (!params) params = {};

    var url = this.urls.base+"/"+controller+"/"+action+"?callback=?";
    if (params.callback)
        url = this.urls.base+"/"+controller+"/"+action+"?callback="+params.callback;
    url = url + "&_"+new Date();
    delete params.callback;
    $.ajax({
        url: url,
        data: params,
        crossDomain:true,
        dataType:'jsonp',
        cache:false,
        ajaxOptions: {cache: false},
        jsonp: params.callback?false:true,
        success:function(data,status){
            if (eventName && eventName!=""){
                $($myapi).trigger(eventName,data);
            }
        }
    });
},
    level: {
    list: function(params){
        params = params || {};
        params.max = params.max!=undefined?parseInt(params.max):$myapi.defaults.levels.max;
        params.page = params.page!=undefined?parseInt(params.page):$myapi.defaults.levels.page;
        params.showActives = params.showActives!=undefined?params.showActives:$myapi.defaults.levels.showActives;
            $myapi._call_myapi_jsonp(params,"level","listJSONP","myapi.level.list");
        },
        info: function(params){
            $myapi._call_myapi_jsonp(params,"level","showJSONP","myapi.level.info");
        }
    }
}

I've been searching through AngularJs Documentation and also searching in Google, but I have not found a way in which the code in Jquery could be made in AngularJS. I thought maybe using $routeProvider it could be done, but I have'nt found any example nor documentation on how to use $routeProvider to make jsonp calls without showing a template or redirecting to some place.

解决方案

It sounds like what you need is a service, akin to what's being done here:

Recommended way of getting data from the server

http://jsfiddle.net/wpPhY/

but with the inclusion of $resource:

http://docs.angularjs.org/api/ngResource.$resource

Here's a basic example of a JSONP service to query Twitter (taken from http://egghead.io):

JSFiddle Demo: http://jsfiddle.net/gavinfoley/DJ6da/

angular.module('Twitter', ['ngResource']);

angular.module('Twitter')
.controller('TwitterCtrl', ['$scope', '$resource', function ($scope, $resource) {
    $scope.twitter = $resource('http://search.twitter.com/:action',
        {action:'search.json', q:'angularjs', callback:'JSON_CALLBACK'},
        {get:{method:'JSONP'}});

    $scope.doSearch = function () {
        $scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm});
    };
}]);

Also, it would be worth taking a look at using Breeze with Angular. I haven't used it myself but you can create some really cool CRUD apps with it:

http://www.breezejs.com/samples/todo-angular

If however you're looking to gain access to functions or properties defined inside of a particular Angular controller (or scope) from jQuery, take a look at the Plnkr and code below.

To be honest, I really wouldn't go down this road if at all possible. It would be better to remove jQuery from your solution altogether and just stick with Angular. Meaning write your Angular API or service and consume it using Angular controllers/directives etc.

In other words, if you're going to use Angular in your application then go "all Angular". Don't try to mix and match with jQuery. It will only slow you down and make your code harder to maintain.

Full Plnkr Demo: http://plnkr.co/edit/X5SfKD?p=preview

HTML

<!DOCTYPE html>
<html data-ng-app="myApp">
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    <script src="myApp.js"></script>
    <script src="script.js"></script>
  </head>
  <body>    
    <div id="parent" data-ng-controller="ParentCtrl">     
        <span id="someSpan">This is {{name}}.</span>    
        <div id="child" data-ng-controller="ChildCtrl">This is {{name}}.</div>    

        Get latest tweet for: <input type="text" data-ng-model="twitterUser" />

        <button data-ng-click="getLatestAngularTwitterPost()">Get Tweet</button><br/><br/>

        Latest {{searchTerm}} Twitter post:
        <div>        
            <img id="twitterProfileImage" data-ng-src="{{profileImage}}" />
            <span data-ng-bind-html-unsafe="tweet" id="tweet"></span>
        </div>    
    </div>    
  </body>
</html>

Angular app - myApp.js

angular.module('myApp', []);

angular.module('myApp')
.controller('ParentCtrl', function ($scope,  $http) {
    $scope.name = "parent";    
    $scope.testFunc = function () {
        return "Test is working."
    };
    $scope.twitterUser = "AngularJS";
    $scope.tweet;
    $scope.profileImage;
    $scope.searchTerm;

    // Returns latest post on Twitter from AngularJS
    $scope.getLatestAngularTwitterPost = function (callbackFunc) {        
        $scope.searchTerm = $scope.twitterUser;        
        var url = "http://api.twitter.com/1/users/show.json";

        $http.jsonp(url, {
          params: {
            callback: 'JSON_CALLBACK',
            screen_name: $scope.twitterUser
          }
        })
        .success(function(data){
            if(callbackFunc){
                console.log("Passing twitter results to callback: " + callbackFunc.name);
                return callbackFunc(data);
            }

            $scope.tweet = data.status.text;
            $scope.profileImage = data.profile_image_url;          
        })
        .error(function() {
            $scope.tweet = "<strong>Error: could not make JSONP request to Twitter.</strong>"; 
        });
    };
});

angular.module('myApp')
.controller('ChildCtrl', function ($scope) {
    $scope.name = "child";
});

jQuery - script.js

// Ex. of how to call methods and update properties 
// in Angular controllers, from jQuery
$(function () {
    // Get Angular controller "ParentCtrl".
    // Could also use $('#someSpan').scope(); to get "ParentCntl" scope
    var $scopeParentCtrl = $('#parent').scope();
    // Get Angular controller "ChildCtrl".
    var $scopeChildCtrl = $('#child').scope();

    // Update the "name" property in Angular controller "ParentCtrl"
    $scopeParentCtrl.$apply(function(){
      $scopeParentCtrl.name = "Joe";
      console.log("Parent name changed to " + $scopeParentCtrl.name);
    });

    // Update the "name" property in Angular controller "ChildCtrl"
    $scopeChildCtrl.$apply(function(){
      $scopeChildCtrl.name = "Gavin";
      console.log("Child name changed to "+ $scopeChildCtrl.name);
    });

    // Call the "testFunc" function in Angular conroller "ParentCtrl"
    console.log($scopeParentCtrl.testFunc());

     // Call the JSONP function in Angular controller "ParentCtrl"
    $scopeParentCtrl.getLatestAngularTwitterPost(jsonpCallback);      
});

function jsonpCallback(data) {
    var $scopeParentCtrl = $('#parent').scope();
    $scopeParentCtrl.tweet = data.status.text;
    $scopeParentCtrl.profileImage = data.profile_image_url;
}

这篇关于在 AngularJS 中创建一个 JSONP API &amp;使用 jQuery 消费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆