Angularjs How to use or inject third-party libraries
I found the example in Deployd website nice, but it’s only consuming rest API data and I’d like to understand how to have Deployd as a service inside AngularJS. For example, keeping all of the clients API up-to-date with the collection’s latest data with collection events available in deployd.
I came up with the example below, where we can see that I’m using $resource to consume the rest api, but inside the controller “MyCtrl”, I’m calling dpd, that I’d like to use to take advantage of features such as notifying-clients
Generally speaking things that handle calls to the server are best encapsulated in services and to encapsulate any DOM manipulation code into directives as shown here
angular.module('questions', ['ngResource'])
.factory('Deployd', function(){
return dpd;
})
.factory('EntriesService', function($resource){
return $resource('/entries', {});
})
.controller('MainCtrl', ['$scope', 'EntriesService', 'Deployd', function($scope, EntriesService, Deployd) {
$scope.title = "Q&A Module";
$scope.entries = [];
EntriesService.query(function(response){
$scope.entries = response;
});
$scope.addMessage = function() {
var author = "myAuthor";
var message = $scope.message;
Deployd.entries.post({
author: author,
message: message
}, function(comment, error) {
if (error) {
return showError(error);
}
$scope.entries.push({
author: author,
message: message
});
});
};
Deployd.entries.on('create', function() {
EntriesService.query(function(response){
$scope.entries = response;
});
});
}]);
Three years later after this post, the following is suggested the following approach for Angular 1.5+
To inject an external library by using a constant.
For example, to inject d3.js into an AngularJS component:
First install d3 with npm install d3 –save, then import it into your app module and then inject it as a constant to your component.
In app.module:
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 my-component:
// 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
};