AngularJS + RequireJS + angular-ui-grid - angularjs

I am trying to use angular-ui-grid with AngularJS and RequireJS. See plunker here.
My index31.html has grid and indexController.js defines the gridOptions object. indexController is injected when needed.
When browser loads indexController.js before index31.html, it works fine (i.e. grid is displayed) but when it is the other way round, I get error: $scope.uiGrid is undefined.
How do I specify (in $stateProvider config or elsewhere) to always load indexController.js before index31.html. Or, how do I make all controllers load before the html?

The reason for this is that you require the actual code of the controller asynchronously, i.e. with an inline require:
// app.js
define(function () {
...
app.controller('IndexController', ['$scope', '$injector', function ($scope, $injector) {
// HERE!!!
require(['indexController'], function (controller) {
$injector.invoke(controller, this, { '$scope': $scope });
});
}]);
});
There is no guarantee for the order of loading with this pattern.
What can you do: Require the 'indexController' at the top:
define(['indexController'], function (indexController) {
...
app.controller('IndexController', indexController);
});
It even removes the (horrible IMO) usage of $injector!
(Sidenote: Doing this, the plunk complained about the $scope.$apply() in the last line of indexController.js; I commented it out, it really seems redundant.)
Plunk: http://plnkr.co/edit/fsyljR8FEeZdvXB3SRJP?p=preview

Related

Angular UI Bootstrap Modal: [$injector:unpr] Unknown provider: $uibModalInstanceProvider

This is a bit strange. When I search this issue online I see many pages of Google results and SO solutions... but none seem to work!
In a nutshell, I am trying to implement AngularUI Bootstrap Modal. I keep getting the following error:
Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- addEntryCtrl
Here is my HTML:
<nav class="navbar navbar-default">
<div class="container">
<span class="nav-col" ng-controller="navCtrl" style="text-align:right">
<a class="btn pill" ng-click="open()" aria-hidden="true">Add New</a>
</span>
</div>
</nav>
Here is my controller:
var app = angular.module('nav', ['ui.bootstrap']);
app.controller('navCtrl', ['$scope', '$uibModal', function($scope, $uibModal) {
$scope.open = function() {
var uibModalInstance = $uibModal.open({
animation: true,
templateUrl: 'addEntry/addEntry.html',
controller: 'addEntryCtrl',
});
};
}]);
And finally, here is my modal code:
var app = angular.module('addEntry', ['firebase', 'ui.bootstrap']);
app.controller('addEntryCtrl', ['$scope', '$firebaseObject', '$state', '$uibModalInstance', function($scope, $firebaseObject, $state, $uibModalInstance) {
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$uibModalInstance.close();
}]);
Solutions I've tried:
updated both Angular Bootstrap (Version: 0.14.3) and Angular (v1.4.8)
changed uibModalInstance to modalInstance
changed $uibModalInstance to modalInstance
put my addEntryCtrl inside my ModalInstance
Any thoughts? This has been driving me up the wall for almost 2 days now.
* EDIT *
I should note two things:
1) when I remove $uibModalInstance as a dependency from addEntry, my HTML form submit buttons work just fine and the form looks perfect. Even the redirect occurs correctly (upon submission). The problem remains: the modal still stays on the screen and an error is thrown that $uibModalInstance is undefined. This makes sense since I removed it as a dependency but I obviously still need the modal is close upon submission.
2) Also, I have almost identical code working in another part of my app. The only difference there is that it's working via a factory. Otherwise, the code is identical. Thus, I am confident my dependencies are all there and versions are correct. So. Freaking. Strange.
Thanks!
Answer Found! After hacking away with my friend, we discovered the answer. I wanted to post it here just in case someone else reads this.
It turns out that we had an ng-controller in our modal window that was in a div tag that wrapped the entire html form that was in the modal. Previously, this worked fine when our form was NOT in a modal (it had a separate URL) but for some reason it breaks when it is in a modal. The ng-controller was referencing the addEntryCtrl. Immediately after removing it, the form worked!
The problem was that you were specifying a (or double) controller(s) in 2 places- when opening a modal and inside a template - this is not needed. Remove ng-controller from a template and things will work as expected.Trust me,it will work.
It turns out that if you specify the controller inside the html template (with ng-controller="...") it will not resolve the $uibModalInstance. Specifying the controller from the call to $uibModal.open({controller="...", ...}) will allow it to resolve correctly.
Since you only need the dismiss() and close() methods, you can get them from $scope (named $dismiss and $close) instead, since that will resolve correctly in both ways of instantiating the controller.
var app = angular.module('addEntry', ['ui.bootstrap']);
app.controller('addEntryCtrl', ['$scope', function($scope) {
$scope.cancel = function() {
$scope.$dismiss('cancel');
};
$scope.$close();
}]);
You are trying to reference a controller that is part of a separate module. In order for this to work, you need to inject your secondary module (addEntry) into your main module (nav):
var app = angular.module('nav', ['ui.bootstrap', 'addEntry']);
As you use $uibModal.open() (see lower) and specify explicitly the controller name, you shouldn't put the directive ng-controller in the template.
That cause the error. No ng-controller in the View !
var uibModalInstance = $uibModal.open({
animation: true,
templateUrl: 'addEntry/addEntry.html',
controller: 'addEntryCtrl',
});

AngularJS - Running a function once on load

I am trying to run an $http function when my AngularJS application first loads.
This $http function needs to finish before any of the controllers in my application could properly function. How would I go about doing this? This sounds like a promise, but it sounds like I would be creating a promise in each controller...
I currently have the function that I want to run first like this:
app.run(function() {
$http.get('link').success(function(data) {
// success function. The data that I get from this HTTP call will be saved to a service.
}).error(function(error) {
});
});
However, sometimes the controller will load before the http call finishes.
The problem
Angular is not dynamic, you cannot add controller dynamically neither factory, etc. Also you cannot defer controller bootstrap, angular loads everything together, and it's quite disadvantage (will be fixed in Angular 2)
The cure
But javascript itself has very important feature - closure, which works anywhere, anytime.
And angular has some internal services that can be injected outside of angular ecosystem, even into browser console. Those services injected as shown below. We technically could use anything else (jQuery.ajax, window.fetch, or even with XMLHttpRequest), but let's stick with total angular solution
var $http_injected = angular.injector(["ng"]).get("$http");
The act
First of all, we defer whole angular app bootstrap, inject http service. Then you make your needed request, receive data and then closure get's to work, we pass received data into some service, or we could also assign in to some angular.constant or angular.value but let's just make demo with angular.service, so when your service has data, bootstrap whole app, so that all controllers get initialized with your needed data
Basically that kind of tasks solved like this
<body>
<div ng-controller="Controller1">
<b>Controller1</b>
{{text}}
{{setting.data.name}}
</div>
<hr>
<div ng-controller="Controller2">
<b>Controller2</b>
{{text}}
{{setting.data.name}}
</div>
<script>
//define preloader
var $http_injected = angular.injector(["ng"]).get("$http");
$http_injected.get('http://jsonplaceholder.typicode.com/users/1').then(function(successResponse) {
//define app
angular.module('app', []);
//define test controllers
//note, usually we see 'controller1 loaded' text before 'settings applied', because controller initialized with this data, but in this demo, we will not see 'controller1 loaded' text, as we use closure to assign data, so it's instantly changed
angular.module('app').controller('Controller1', function($scope, AppSetting) {
$scope.text = 'controller1 loaded';
$scope.setting = AppSetting.setting;
$scope.$watch('setting', function(e1 ,e2){
$scope.text = 'settings applied'
});
});
angular.module('app').controller('Controller2', function($scope, AppSetting) {
$scope.text = 'controller2 loaded';
$scope.setting = AppSetting.setting;
$scope.$watch('setting', function(e1 ,e2){
$scope.text = 'settings applied'
});
});
//define test services, note we assign it here, it's possible
//because of javascript awesomeness (closure)
angular.module('app').service('AppSetting', function() {
this.setting = successResponse;
});
//bootstrap app, we cannot use ng-app, as it loads app instantly
//but we bootstrap it manually when you settings come
angular.bootstrap(document.body, ['app']);
});
</script>
</body>
Plunker demo
You can do this when you configure your routes
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'main.html',
resolve: {
data: ['$http',
function($http)
{
return $http.get('/api/data').then(
function success(response) { return response.data.rows[0]; },
function error(reason) { return false; }
);
}
]
}
});
}]);
Similar question:
AngularJS - routeProvider resolve calling a service method
AngularJS: $routeProvider when resolve $http returns response obj instead of my obj
Heres a plunkr I found using a service, which is what I would recommend.
http://plnkr.co/edit/XKGC1h?p=info

Why does an Angular controller that is a function work, but a controller in a package does not?

In a recent question, I was having an issue with a simple modal dialog implemented using Angular UI for Bootstrap.
I started with this fiddle, and the person who answered came up with this result.
However, one thing immediately caught my attention!
Old Controller Implementation
var controllers = angular.module('app.controllers', []);
controllers.controller('ModalController', ['$scope', '$modal', '$log',
function ($scope, $modal, $log) {
// Overarching controller code...
}
]);
controllers.controller('ModalInstanceController', ['$scope', '$modalInstance',
function ($scope, $modalInstance, params) {
// ...Modal Instance Code...
}
]);
This code does not work with the Angular UI for Bootstrap Modal, but for some reason, this code does:
var ModalController = function($scope, $modal, $log) {
// Overarching controller code...
};
var ModalInstanceController = function($scope, $modalInstance, params) {
// Modal Instance Code...
};
...The problem being, that AngularJS code is usually modularized like the first example to avoid cluttering the global namespace.
So far none of my experiments have been able to get a modularized setup to succeed in the first place. I attempted some simple substitutions, where I would make one controller or the other be a modularized controller, in hopes that it was only one controller preventing the params from being passed between controllers; this turned out not to be the case. Implementing $scope.params = []; before declaring the $scope.open() function, and populating $scope.params in the open function similarly had no effect.
Question: In the context of the AngularUI for Bootstrap system, why does the modularized approach fail? And more importantly, how can I make it work?
Here is your fixed plnkr (http://jsfiddle.net/pEmXt/4/), it had several problems:
You defined your modules in the wrong order.
You had the ui DI in the wrong place.
Your resolve syntax was wrong.
The DI in your modal instance controller was missing an item in the list of dependencies.
The resolve method is used like this:
resolve: {
objectName: function(){
return myObject;
}
}
OK...so I recently ran into same issue and was perplexed also. I just never bothered to dig into it. A quick trip to angular-ui github repo and I found out in the issue tracker.
Angular-Ui demos are passing a function reference as controller. For a modular controller it needs to be a string
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl', /* use string for modular controller */
/* OR */
controller: ModalInstanceCtrl, /* use reference for controller as function*/
});
Issue tracker reference: https://github.com/angular-ui/bootstrap/issues/2330
Working demo from issue tracker: http://plnkr.co/edit/38vBcPalBBNMgYis4cZX?p=preview
In the first example, the module 'app.controllers' has to be added to the list of dependencies for the main app.
var app = angular.module('app', ['app.controllers']);
In the second instance the controllers are global functions and therefore are visible without being explicitly added as a dependency.

AngularJS 1.x custom filter can't be injected, unknown provider

I'm trying to create a custom filter, but when I try to inject it into my controller, I get an 'Unknown provider' error. I have checked and double checked all the references, but I can't see what's wrong.
I know that the file is referenced in my index.html correctly, it is loaded and can be found by the inspector. This is the code I have:
In my app.js:
angular.module('equiclass', ['equiclass.controllers',
'equiclass.services',
'ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/courses', {
templateUrl: 'views/courses.html',
controller: 'CourseCtrl'
// And some other stuff with routes
});
angular.module('equiclass.controllers', ['equiclass.services', 'equiclass.filters']);
angular.module('equiclass.services', []);
angular.module('equiclass.filters', []);
My filter:
angular.module('equiclass.filters')
.filter('testFilter', function() {
return function(input) {
return undefined;
};
});
And the controller:
angular.module('equiclass.controllers')
.controller('CourseCtrl', function ($scope, testFilter) {
});
Of course this is quite simplified, but it just doesn't work, and I can't see why. I have made several services and they all work and play along nicely.
If you want to use filter inside a controller you have to inject $filter attribute to your controller and can access it like
$filter('filtername');
You can use like
function myCtrl($scope, $filter)
{
$filter('filtername')(arg1,arg2);
}
You don't need to inject the filter itself.
This code...
angular.module('equiclass.controllers')
.controller('CourseCtrl', function ($scope, testFilter) {
});
Should be
angular.module('equiclass.controllers')
.controller('CourseCtrl', function ($scope) {
});
And inside CourseCtrl you should use your filter as you normally do.
Injecting the module 'equiclass.filters' into your module 'equiclass.controllers' is enough.
I had a similar issue and made a post about it on my blog.
--Edit
As n00dl3 mentions below the tricky part is how the auto-naming convention works in Angular. If you name your filter specialNumberFilter then when you inject it you need to refer to it as specialNumberFilterFilter. This allows you to use the filter as a function, which is what it is.
// In a controller
vm.data = specialNumberFilterFilter(vm.data, 'a');
But I believe you can also use the filter without injecting it into a controller if it is used in a string expression that is being evaluated by, say, a watch because this would be the same as the scenario when you are using it in a template.
// Inside a watch - no controller injection required
`$scope.$watch('vm.data | specialNumberFilter', function(new, old) { ... })`
According to Angular's documentation :
if you want to use your filter in a template
then you just need to inject it in your module and then use it like this {{ expression | filter }} or {{ expression | filter:argument1:argument2:... }} .
doc
if you want to use your filter in a controller, directive, and stuffs :
inject a dependency with the name <filterName>Filter, like this :
controller('MyController', ['filterFilter', function(filterFilter) {}]);
doc
so for this particular case :
angular.module('equiclass.controllers')
.controller('CourseCtrl', function ($scope, testFilterFilter) {
});
you didn't mention if it's in production or on a local server, but just in case you are minifying your files, try this:
angular.module('equiclass.controllers')
.controller('CourseCtrl', ['$scope', 'testFilter', function ($scope, testFilter) {
}]);

$routeParams is empty in main controller

I have this piece of layout html:
<body ng-controller="MainController">
<div id="terminal"></div>
<div ng-view></div>
<!-- including scripts -->
</body>
Now apparently, when I try to use $routeParams in MainController, it's always empty. It's important to note that MainController is supposed to be in effect in every possible route; therefore I'm not defining it in my app.js. I mean, I'm not defining it here:
$routeProvider.when("/view1", {
templateUrl: "partials/partial1.html"
controller: "MyCtrl1"
})
$routeProvider.when("/view2", {
templateUrl: "partials/partial2.html"
controller: "MyCtrl2"
})
// I'm not defining MainController here!!
In fact, I think my problem is perfectly the same as this one: https://groups.google.com/forum/#!topic/angular/ib2wHQozeNE
However, I still don't get how to get route parameters in my main controller...
EDIT:
What I meant was that I'm not associating my MainController with any specific route. It's defined; and it's the parent controller of all other controllers. What I'm trying to know is that when you go to a URL like /whatever, which is matched by a route like /:whatever, why is it that only the sub-controller is able to access the route parameter, whereas the main controller is not? How do I get the :whatever route parameter in my main controller?
The $routeParams service is populated asynchronously. This means it will typically appear empty when first used in a controller.
To be notified when $routeParams has been populated, subscribe to the $routeChangeSuccess event on the $scope. (If you're in a component that doesn't have access to a child $scope, e.g., a service or a factory, you can inject and use $rootScope instead.)
module.controller('FooCtrl', function($scope, $routeParams) {
$scope.$on('$routeChangeSuccess', function() {
// $routeParams should be populated here
});
);
Controllers used by a route, or within a template included by a route, will have immediate access to the fully-populated $routeParams because ng-view waits for the $routeChangeSuccess event before continuing. (It has to wait, since it needs the route information in order to decide which template/controller to even load.)
If you know your controller will be used inside of ng-view, you won't need to wait for the routing event. If you know your controller will not, you will. If you're not sure, you'll have to explicitly allow for both possibilities. Subscribing to $routeChangeSuccess will not be enough; you will only see the event if $routeParams wasn't already populated:
module.controller('FooCtrl', function($scope, $routeParams) {
// $routeParams will already be populated
// here if this controller is used within ng-view
$scope.$on('$routeChangeSuccess', function() {
// $routeParams will be populated here if
// this controller is used outside ng-view
});
);
As an alternate to the $timeout that plong0 mentioned...
You can also inject the $route service which will show your params immediately.
angular.module('MyModule')
.controller('MainCtrl', function ($scope, $route) {
console.log('routeParams:'+JSON.stringify($route.current.params));
});
I have the same problem.
What I discovered is that, $routeParams take some time to load in the Main Controller, it probably initiate the Main Controller first and then set $routeParams at the Child Controller. I did a workaround for it creating a method in the Main Controller $scope and pass $routeParams through it in the Child Controllers:
angular.module('MyModule')
.controller('MainController', ["$scope", function ($scope) {
$scope.parentMethod = function($routeParams) {
//do stuff
}
}]);
angular.module('MyModule')
.controller('MyCtrl1', ["$scope", function ($scope) {
$scope.parentMethod($routeParams);
}]);
angular.module('MyModule')
.controller('MyCtrl2', ["$scope", function ($scope) {
$scope.parentMethod($routeParams);
}]);
had the same problem, and building off what Andre mentioned in his answer about $routeParams taking a moment to load in the main controller, I just put it in a timeout inside my MainCtrl.
angular.module('MyModule')
.controller('MainCtrl', function ($scope, $routeParams, $timeout) {
$timeout(function(){
// do stuff with $routeParams
console.log('routeParams:'+JSON.stringify($routeParams));
}, 20);
});
20ms delay to use $routeParams is not even noticeable, and less than that seems to have inconsistent results.
More specifically about my problem, I was confused because I had the exact same setup working with a different project structure (yo cg-angular) and when I rebuilt my project (yo angular-fullstack) I started experiencing the problem.
You have at least two problems here:
with $routeParams you get the route parameters, which you didn't define
the file where you define a main controller doesn't really matter. the important thing is in which module/function
The parameters have to be defined with the $routeProvider with the syntax :paramName:
$routeProvider.when("/view2/name1/:a/name2/:b"
and then you can retrieve them with $routeParams.paramName.
You can also use the query parameters, like index.html?k1=v1&k2=v2.
app.js is the file where you'd normally define dependencies and configuration (that's why you'd have there the app module .config block) and it contains the application module:
var myapp = angular.module(...);
This module can have other modules as dependencies, like directives or services, or a module per feature.
A simple approach is to have a module to encapsulate controllers. An approach closer to your original code is putting at least one controller in the main module:
myapp.controller('MainCtrl', function ($scope) {...}
Maybe you defined the controller as a global function? function MainCtrl() {...}? This pollutes the global namespace. avoid it.
Defining your controller in the main module will not make it "to take effect in all routes". This has to be defined with $routeProvider or make the controller of each route "inherit" from the main controller. This way, the controller of each route is instantiated after the route has changed, whereas the main controller is instantiated only once, when the line ng-controller="MainCtrl" is reached (which happens only once, during application startup)
You can simply pass values of $routeParams defined into your controller into the $rootScope
.controller('MainCtrl', function ($scope, $routeParams, MainFactory, $rootScope) {
$scope.contents = MainFactory.getThing($routeParams.id);
$rootScope.total = MainFactory.getMax(); // Send total to the rootScope
}
and inject $rootScope in your IndexCtrl (related to the index.html)
.controller('IndexCtrl', function($scope, $rootScope){
// Some code
});

Resources