AngularJS:如何在 AngularJS 中使用或注入第三方库

2024-05-05

我是 Angular 和 Deployd 的新手,想知道如何一起使用它们。

我发现 Deployd 网站中的示例很好,但它只消耗其余 API 数据,我想了解如何将 Deployd 作为 AngularJS 中的服务。例如,通过部署中可用的收集事件,使所有客户端 API 保持最新的收集最新数据。

我想出了下面的示例,我们可以看到我正在使用 $resource 来使用其余 api,但在控制器“MyCtrl”内,我正在调用 dpd,我想用它来利用特点如http://docs.deployd.com/docs/collections/notifying-clients.md http://docs.deployd.com/docs/collections/notifying-clients.md

我真的很想看到一些例子,或者对此有任何建议!

感谢您的浏览:)

angular.module('questions', ['ngResource'])

.factory('Deployd', function(dpd){
  return dpd;
})

.factory('EntriesService', function($resource){
  return $resource('/entries', {});
})

.controller('MainCtrl', ['$scope', 'EntriesService', function($scope, EntriesService) {

  $scope.title = "Q&A Module";

  $scope.entries = [];

  EntriesService.query(function(response){
    $scope.entries = response;       
  });

  $scope.addMessage = function() {
    $scope.entries.push({
        author: "myAuthor",
        message: $scope.message
    });

    EntriesService.save({
        author: "myAuthor",
        message: $scope.message
    });

  };

  dpd.comments.get(function(comments, error) {
    comments.forEach(function(comment) {
      console.log(comment);
    });
  });

}]);

如果您使用 AngularJS 1.5+成分 https://docs.angularjs.org/guide/component和 ES2015/ES6,您可以通过使用注入外部库constant https://docs.angularjs.org/api/auto/service/%24provide#constant.

例如,要注入d3.js进入 AngularJS 组件:

首先安装 d3npm install d3 --save,然后将其导入到您的应用程序模块中,然后将其作为常量注入到您的组件中。

in 应用程序模块:

import * as d3 from 'd3';
import { MyComponent } from './my-component/my-component';

export default angular.module('app', [])
    .constant('d3', d3)
    .component('myComponent', MyComponent)
    .name;

in 我的组件:

// Controller
class MyController {
    constructor(d3, $element) {
        this.d3 = d3;
        this.$element = $element;
    }

    $onInit() {
        // $element is the jqLite or jQuery component's element and 
        // $element[0] is the DOM node element
        this.d3.select(this.$element[0]).append('p').text('Hello world');
    }
}

// Component
export var MyComponent = {
    template: require('./my-component.html'),
    controller: MyController
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJS:如何在 AngularJS 中使用或注入第三方库 的相关文章

随机推荐