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

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

问题描述

现在我已经创建了jQuery的一个JS API,但我不知道它是否能与AngularJs来完成。

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

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

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");
        }
    }
}

我一直在寻找通过AngularJs文档,也搜索在谷歌,但我还没有发现在jQuery中的code可在AngularJS作出的一种方式。
我想,也许使用$ routeProvider这是可以做到的,但我发现have'nt关于如何使用$ routeProvider做出而不显示模板或重定向到某个地方JSONP调用的任何例子也不文档。

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:

<一个href=\"http://stackoverflow.com/questions/11850025/recommended-way-of-getting-data-from-the-server/11850027#11850027\">Recommended从服务器获取数据的方式

http://jsfiddle.net/wpPhY/

但列入 $资源的:

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

下面是一个JSONP服务来查询的Twitter的一个基本的例子(从 http://egghead.io 服用):

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

的jsfiddle演示: 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});
    };
}]);

此外,这将是值得考虑看看在使用微风角。我没有用它自己,但你可以用它创建一些很酷的CRUD应用程序:

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

然而,如果你正在寻找获得jQuery的从一个特定的角度控制器(或范围)内定义的函数或属性,看看在Plnkr及以下code。

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.

说实话,我真的不走这条路,如果在所有可能的。这将是更好干脆从解决方案中删除的jQuery和公正的坚持与棱角分明。这意味着你编写API角或服务,并采用了棱角分明的控制器/指令等消费它。

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.

在换句话说,如果你要使用你的应用程序角然后进入全角。不要试图混搭使用jQuery。它只会减慢你的速度,让你的code难以维持。

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.

全Plnkr演示: 的http:// plnkr。 CO /编辑/ 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>

角应用 - 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;使用jQuery消费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆