Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject module dependency (like plugin) only if needed AngularJS

I have 2 pages (I don't use the angular's routing - This constraint).

In one of them I want to use the directive ui-grid like in this demo:

var app = angular.module('myApp', ['ui.grid']);
app.controller('mainCtrl', function($scope) {
  $scope.myData = [
    {
        "firstName": "Cox",
        "lastName": "Carney",
        "company": "Enormo",
        "employed": true
    },
    {
        "firstName": "Lorraine",
        "lastName": "Wise",
        "company": "Comveyer",
        "employed": false
    },
    {
        "firstName": "Nancy",
        "lastName": "Waters",
        "company": "Fuelton",
        "employed": false
    }
  ];
});
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">

<div ng-app="myApp">
  <div ng-controller="mainCtrl">
    <div id="grid1" ui-grid="{ data: myData }" class="grid"></div>
  </div>
</div>

My question is if there is a way to not inject the ui-grid dependency to the app in any case but only when I need it.

Something like:

app.controller('mainCtrl', function($scope) {
   app.$inject('ui-grid');
});

Update

I tried to do:

var ui_grid = $injector.get('ui-grid');

But I've got an error:

Unknown provider: ui-gridProvider <- ui-grid

http://errors.angularjs.org/1.2.26/$injector/unpr?p0=ui-gridProvider%20%3C-%20ui-grid

like image 651
Mosh Feu Avatar asked Dec 17 '15 08:12

Mosh Feu


2 Answers

Core Angular API does not provide this feature. ocLazyLoad is the popular library for lazy loading of modules and components in Angular.

You can find more info on their page: https://oclazyload.readme.io

or the GitHub repository: https://github.com/ocombe/ocLazyLoad

like image 96
S.Klechkovski Avatar answered Nov 11 '22 00:11

S.Klechkovski


Core Angular API does provide this feature, simply use 'requires' property of module @ Properties section @ https://code.angularjs.org/1.4.7/docs/api/ng/type/angular.Module

var app = angular.module('myApp');

//Page 1 JS
//change below statement as per requirement in different pages
app.requires = ['ui.grid'];
app.controller('mainCtrl1', function($scope) {

}

//Page 2 JS
app.requires = ['ngResource', 'ui.bootstrap', 'ui.calendar'];
app.controller('mainCtrl2', function($scope) {

}

ocLazyLoad is also good solution, but I guess 'requires' property will solve your problem without much effort.

like image 23
FixBug Tester Avatar answered Nov 11 '22 01:11

FixBug Tester