在 AngularJS 中创建 JSONP API 并使用 jQuery 使用



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

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

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中的代码可以在AngularJs中制作。我想也许使用$routeProvider可以做到,但我没有找到关于如何使用$routeProvider进行jsonp调用而不显示模板或重定向到某个地方的任何示例或文档。

听起来你需要的是一个服务,类似于这里所做的:

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

http://jsfiddle.net/wpPhY/

但包含$resource:

http://docs.angularjs.org/api/ngResource。美元资源

下面是一个查询Twitter的JSONP服务的基本示例(取自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});
    };
}]);

同样,在Angular中使用Breeze也值得一试。我自己没有使用过它,但是你可以用它创建一些非常酷的CRUD应用程序:

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

如果你想从jQuery中访问特定Angular控制器(或作用域)中定义的函数或属性,请查看下面的Plnkr和代码。

老实说,如果可能的话,我真的不会走这条路。最好把jQuery从你的解决方案中完全移除,只使用Angular。这意味着编写你的Angular API或服务,并使用Angular控制器/指令等来消费它。

换句话说,如果你打算在你的应用中使用Angular,那就选择"全部使用Angular"。不要尝试与jQuery混搭。它只会减慢你的速度,使你的代码更难维护。

完整的Plnkr演示: http://plnkr.co/edit/X5SfKD?p=preview

<!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;
}

最新更新