jquery - 在 AngularJS 中创建 JSONP API 并使用 jQuery 进行使用

标签 jquery api angularjs jsonp angularjs-scope

现在我已经使用 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 文档,也在 Google 中搜索,但我还没有找到一种方法可以在 AngularJS 中编写 Jquery 中的代码。 我想也许使用 $routeProvider 可以完成,但我没有找到任何关于如何使用 $routeProvider 进行 jsonp 调用而不显示模板或重定向到某个地方的示例或文档。

最佳答案

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

Recommended way of getting data from the server

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('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});
    };
}]);

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

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

但是,如果您希望从 jQuery 访问特定 Angular Controller (或范围)内定义的函数或属性,请查看下面的 Plnkr 和代码。

说实话,如果可以的话我真的不会走这条路。最好从您的解决方案中完全删除 jQuery,而只使用 Angular。这意味着编写 Angular API 或服务并使用 Angular Controller /指令等使用它。

换句话说,如果您要在应用程序中使用 Angular,那么就选择“全部 Angular”。不要尝试与 jQuery 混合搭配。它只会减慢您的速度并使您的代码更难以维护。

完整 Plnkr 演示: 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 应用程序 - 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;
}

关于jquery - 在 AngularJS 中创建 JSONP API 并使用 jQuery 进行使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16195199/

相关文章:

javascript - 在现有 json 对象中添加新键(数组)

javascript - 复制 Netflix 登录并生成 cookie

php - 如何对齐页面右侧的链接/图片列表,并阻止它们重叠?

javascript - 表单代码在 Firefox 中不起作用(提交和警报)

javascript - 减去文档片段滚动的垂直偏移

python - Soundcloud API 在某些轨道上返回 403

javascript - 数据未传递给 api 调用

javascript - 使用 AngularJS 单击搜索结果时将输入重置为初始值

jquery - 如何使用 Bootstrap 3 使图像全宽

javascript - PHP 表单适用于索引,但不适用于联系我们页面