Reputation: 1187
I am wondering whether it is possible to build an independent directive.
I am very new on AngularJS, please, let me know if there are deep conceptual mistakes in what I am looking for.
My current "try" is:
(function () {
// a module for holding the directive
var app = angular.module('monitorApp', []);
// a service for getting some data
app.service("MonitorService", function ($http, $q) {
return ({
getMonitorInfo: getMonitorInfo
});
function GetMonitorInfo() {
var request = $http({
method: "get",
url: "/IndicatorsReport/GetMonitorInfo"
});
return (request.then(notifyErrorIfNeed, handleError));
}
function handleError(response) {
if (!angular.isObject(response.data) || !response.data.message) {
return ($q.reject("An unknown error occurred."));
}
return ($q.reject(response.data.message));
}
function notifyErrorIfNeed(response) {
var data = response.data;
if (data.status !== "success") {
new PNotify({
title: data.title,
text: data.text,
type: 'error',
hide: false,
styling: 'bootstrap3'
});
}
return data;
}
});
// my actual directive
app.directive('monitorButton', function ($document) {
// a self initializing controller
var controller = ['$scope', function ($scope, MonitorService) {
var vm = this;
function init() {
MonitorService.GetMonitorInfo().then(function (data) {
// this is the actual data
vm.feedBots = data.feedBots;
// this is fake data yet
vm.flags = {
cls: 'bg-blue',
number: 3,
show: true
};
});
}
init();
}];
//a very simple template
var template = '<button type="button" class="btn btn-app">' +
' <span class="badge {{vm.flags.cls}}" ng-show="vm.flags.show">{{vm.flags.number}}</span>'+
' <i class="fa fa-dashboard"></i> Monitor'+
'</button>';
// my directive params
return {
restrict: 'EA',
controller: controller,
scope: {},
controllerAs: 'vm',
bindToController: true,
template: template
};
});
}());
I was intending to just add the following code to my html page (along with angularjs off course):
<script src="/app/directives/monitor.js" type="text/javascript"></script>
Finally, I was naively intending to call it like:
<monitor-button></monitor-button>
Edit
It is not working, I am not seeing any element in the page.
Upvotes: 0
Views: 31
Reputation: 2324
For independent Angular application, call angular.bootstrap to bootstrap your app on page,
//monitor.js
(function(){
var app = angular.module('monitorApp', []);
//define your app...
//bootstrap your app...
angular.bootstrap(document, ['monitorApp']);
})()
Upvotes: 1