Issue injecting angular-ui into my controller - angularjs

I have ui.bootstrap as a dependency in my app, but I'm having an issue injecting the $modal service into my controller.
I'm getting the following error:
$modal is not defined
in my controller code, specifically in this function below where I attempt to open a modal :
function saveAndDisplayReport() {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
$location.url('index.html#/?reptname=' + vm.reptName);
}
Here's my reportmaint.js controller code header section, but Im' unclear on how to inject ui.bootstrap (please see the $modal parameter):
(function () {
'use strict';
var controllerId = 'reportmaint';
angular.module('app').controller(controllerId, ['$rootScope', '$scope', '$location', 'common', 'datacontext',
'gridHierarchyService', 'reportsContext', '$modal', reportmaint]);
function reportmaint($rootScope, $scope, $location, common, datacontext, gridHierarchyService, reportsContext) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var logErr = getLogFn("error");
...
})();
and here is my app.js where 'ui.bootstrap' is defined:
(function () {
'use strict';
var app = angular.module('app', [
// Angular modules
'ngAnimate', // animations
'ngRoute', // routing
'ngSanitize', // sanitizes html bindings (ex: sidebar.js)
// Custom modules
'common', // common functions, logger, spinner
'common.bootstrap', // bootstrap dialog wrapper functions
// 3rd Party Modules
'ui.bootstrap', // ui-bootstrap (ex: carousel, pagination, dialog)
'kendo.directives', // Kendo UI
'app.customcontrollers' // Language/Currency settings
//'ngjqxsettings' // jQWidgets init and directives (loaded in index.html)
]);
app.run(['$route', '$rootScope', 'common', 'userService', function ($route, $rootScope, common, userService) {
console.log("In app.run");
var getLogFn = common.logger.getLogFn;
var log = getLogFn('app');
}]);
})();
and in my index.html file I have the script reference :
<script src="scripts/ui-bootstrap-tpls-0.10.0.js"></script>
I am using this plunker as a live example, but I'm still going wrong somewhere - http://plnkr.co/edit/KsADLPaOfY7rtPTdWyYn?p=preview
thanks in advance for your help...
Bob

it seems like you are not injecting the modal at all ($modal is missing) in the function of your controller; try something like:
I'm not sure if reportmaint is a service, if not, just remove it
angular.module('app').controller('reportmaint', ['$rootScope', '$scope', '$location', 'common', 'datacontext','gridHierarchyService', 'reportsContext', '$modal', 'reportmaint',
function($rootScope, $scope, $location, common, datacontext, gridHierarchyService, reportsContext, $modal, reportmaint) {
//Client code
}
]);

Related

angular.js:11598 TypeError: Cannot read property 'open' of undefined in angularjs modal

i try to call modal instance from main page controller but i get this error
TypeError: Cannot read property 'open' of undefined
are anyone help me to solve the problem
my main page controller is
app.controller('unitMasterCntlr', ['$scope', 'toaster', '$state',
'$http', 'emodal', '$timeout', '$compile','$filter','$modal','$rootScope',
function ($scope, toaster, $state, $http, emodal, $timeout, $compile,
DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $interval,$filter,$modal,$rootScope) {
and module is
angular.module('app', ['datatables','ui.select2','easyModalService',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router',
'ui.bootstrap',
'ui.utils',
'ui.load',
'ui.jq',
'oc.lazyLoad',
'pascalprecht.translate',
'ui.mask']);
and modal calling code as
var modalInstance = $modal.open({
templateUrl: 'tpl/UnitMasterModal.jsp',
controller: 'modalcntrl',
size: 'lg',
resolve: {
items: function () {
return $scope.items;
}
}
});
modal controller is
app.controller('modalcntrl', ['$scope', '$modalInstance', 'items', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
where item is an array having some response value that i want to display on modal
iam new to angularjs... plz help me to solve this
I would suggest that this issue is probably caused by a mismatch of your Angular js and Angular Bootstrap UI js libraries.
Please note that the latest version of AngularJS Bootstrap UI 0.12.1 requires Angular 1.2.16+
Check your includes and that the versions are compatible.
problem solved when i change my module like this
app.controller('unitMasterCntlr', ['$scope', 'toaster', '$state','$http', 'emodal', '$timeout', '$compile','$filter','$modal','$rootScope',function ($scope, toaster, $state, $http, emodal,$filter,$modal,$rootScope) {

angular injector error with config()

I want to inject a config into my angular app. The app contains also an run object.
But when I add the config option I get an $injector:modulerr error. And I can't find the error.
var myApp = angular.module('myApp',[
'ngAnimate',
'ui.bootstrap',
'ui.router',
'angular.filter',
'angularUtils.directives.dirPagination',
'validation.match',
'ngSanitize',
'ngCookies',
'pascalprecht.translate',
'toggle-switch',
'angucomplete-alt',
'cgPrompt',
'dndLists',
'ngFileUpload',
'ui.router.breadcrumbs',
'angular-bind-html-compile',
'rzModule', // range slider (i.e. for price filter)
'ngFileSaver',
'angular-input-stars',
'textAngular',
'textAngular-uploadImage'
]);
myApp.config(function($provide) {
$provide.decorator('taOptions', function($delegate) {
$delegate.toolbar[1].push('uploadImage');
return $delegate;
});
});
myApp.run(['$rootScope', '$window', '$location', '$stateParams', '$api', '$translate', '$transitions', '$state',
function($rootScope, $window, $location, $stateParams, $api, $translate, $transitions, $state) {
//rootscope
}]);
It's going about the textAngular-uploadImage module (https://github.com/mrded/textAngular-uploadImage). When I remove the config option my app runs fine, but of course, I can't use the module.
What is the reason for this? I included al the required files in the html, and textAngular (https://github.com/textAngular/textAngular) is working fine.
How can I solve this? Or are there any other options for a normal upload function in textAngular? I also tried this solution (https://github.com/textAngular/textAngular/issues/139#issuecomment-111205679) but I get the same error.
Try something below code..
myapp.config(['$provide', function($provide){
$provide.decorator('taOptions', ['$delegate', function(taOptions){
taOptions.toolbar[1].push('uploadImage');
}
return taOptions;
}];
});
And you would need to register upload image with editor like below
taRegisterTool('uploadImage', {
iconclass: "fa fa-user",
action: function(){
//code
}
});

AngularJS Controller not registered

I'm new using Angular with MVC Web Api but using VB instead of C#. I'm trying to make an SPA web site and I have some week trying to solve this problem.
In my app.js I defined the routing to my views and the controllers I'm going to use in them
var goMessage = angular.module('goMessage', ['ngRoute', 'goMessage.controllers', 'goMessage.services', 'goMessage.directives']);
angular.module('goMessage.controllers', []);
angular.module('goMessage.services', []);
angular.module('goMessage.directives', []);
goMessage.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
//Vista Login
$routeProvider.when('/login/inicio', {
controller: 'loginController',
controllerAs: 'lgCtrl',
templateUrl: 'Home/Login'
});
//Vista Usuarios
$routeProvider.when('/usuarios/lista', {
controller: 'usuariosController',
controllerAs: 'usCtrl',
templateUrl: 'Home/Usuarios'
});
$routeProvider.when('/dashboard/inicio', {
controller: 'dashboardController',
controllerAs: 'dashCtrl',
templateUrl: 'Home/Dashboard'
});
$locationProvider.html5Mode(true);
}]);
The usuariosController.js controller is working very well, its code is:
angular.module('goMessage.controllers')
.controller("usuariosController", ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
//Ordenamiento por default
this.ordenarPorColumna = 'UsuarioID';
this.reverse = false;
// More code...
}
]);
And the loginController.js controller code is:
angular.module('goMessage.controllers')
.controller('loginController', ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
this.myData = "Data$$$";
}
]);
In the Login.vbhtml view I'm following the same pattern as the Usuarios.vbhtml view. I define my ng-app in the _layout.vbhtml and I don't define any controller inside any view.
The error I'm unable to solve is this:
Error Image
Look at the AngularJs Expression
As you can see, I've defined both controller using the same way but the only one that works is the usuarios one and any other controller I add doesn't work.
Here I show you the scripts loading order:
Scripts Loading Order
I'm using my local IIS and working in VS2012.
The angular JS version is 1.6.
To register the logic modules as controller, filter and etc..., you need to add this code in your app.config
var app = angular.module("App", []);
var config = function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.register;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
//your codes
}
config.$inject = ["$controllerProvider", "$compileProvider", "$filterProvider", "$provide"];
app.config(config);
Why this happen?
sometimes we don't need to add all of controllers in our main index which has ng-view or ui-view for that we should put our controller as lazyload to the app.config as you do this in your config, because of that the main app for get the controllers need to register controllers and other modules.
This issue might happen due to asynchronous loading of scripts. The script order might also be an issue. You can add a console.log at the beginning of loginController to check whether the component is loaded correctly.

route provider how to pass a dependency into a controller

if I have the following angularjs code route provider how can I pass through a dependency into the blaCtrl controller please?
Many thanks,
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/bla', { templateUrl: 'bla.html', controller: 'blaCtrl' });
trying to get something like
'use strict';
app.controller('blaCtrl', function ($scope) {
$scope.mydata = ['111', '222', '333']; // how can I change this to be a method call to a dependency, i.e.
$scope.mydata = mydependency.getData(); // example what I need
});
update
My app file looks like this - I'm still not getting the data displayed?
'use strict';
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/application', { templateUrl: 'partials/application.html', controller: 'myCtrl' });
$routeProvider.otherwise({ redirectTo: '/application' });
}]);
controller
'use strict';
app.controller('myCtrl', 'myService', function ($scope, myService) {
debugger; // doesn't get hit?
$scope.stuff = myService.getStuff();
});
console error
- I get this error in the console Error: [ng:areq] http://errors.angularjs.org/1.4.5/ng/areq?p0=applicationCtrl&p1=not%20a%20function%2C%20got%20string
There are 3 ways of dependency annotation according to angular docs.
Inline Array Annotation
In this case your controller defenition should look like:
'use strict';
app.controller('blaCtrl', ['$scope', 'mydependency', function ($scope, mydependency) {
$scope.mydata = mydependency.getData();
}]);
$inject Property Annotation
'use strict';
var blaCtrl = function ($scope, mydependency) {
$scope.mydata = mydependency.getData();
};
blaCtrl.$inject = ['$scope', 'mydependency'];
app.controller('blaCtrl', blaCtrl);
Implicit Annotation
This one you used in your example code to inject $scope variable. Not recommended, minificattion will broke such code.
'use strict';
app.controller('blaCtrl', function ($scope, mydependency) {
$scope.mydata = mydependency.getData();
});
The fact that you reference your controller not in HTML but in routeProvider doesn't make any difference.
You can pass a dependency to the controller from within the controller. You're injecting the $scope dependency already, and you can inject others like $location and $rootScope if you'd like.

Getting controller undefined when trying to run jasmine test

I'm just about to write tests for my angularjs-app. However when Im trying to run the test which is very simpel one i get the following error.
Error: [ng:areq] Argument 'MyPageController' is not a function, got undefined
I'll provide code for the setup of my controllers, config etc.
Route
var myPageApp = angular.module('myPageApp', ['ngRoute', 'ngAnimate', 'ngSanitize', 'app.controller', 'app.service', 'app.filter', 'app.config'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'App_AngularJs/partials/myPage/myPage.htm',
controller: 'MyPageController',
reloadOnSearch: false,
});
}]);
Controller
var myPageApp = angular.module('app.controller', ['oci.treeview', 'ui.bootstrap'])
.controller('MyPageController', ['$scope', '$routeParams', '$location', '$timeout', '$filter', '$modal', 'myPageService',
function ($scope, $routeParams, $location, $timeout, $filter, $modal, myPageService) {
init();
function init() {
$scope.page = { value: $routeParams.page || 1 };
}
}]);
Simpel test
'use strict';
describe('Testing MyPageController', function(){
var scope;
//mock Application to allow us to inject our own dependencies
beforeEach(angular.mock.module('myPageApp'));
//mock the controller for the same reason and include $rootScope and $controller
beforeEach(angular.mock.inject(function($rootScope, $controller){
//create an empty scope
scope = $rootScope.$new();
//declare the controller and inject our empty scope
$controller('MyPageController', { $scope: scope });
}));
// tests start here
it('should map routes to controllers', function () {
module('myPageApp');
inject(function ($route) {
expect($route.routes['/'].controller).toBe('MyPageController');
expect($route.routes['/'].templateUrl).
toEqual('App_AngularJs/partials/myPage/myPage.htm');
});
});
it('should have variable assigned = "1"', function(){
expect(scope.page.value).toBe(1);
});
});
My wildest and best guess is that i need to mock app.controller but how? Everything starts out with myPageApp which holds references to service, controller etc etc..
I think your issue is that routing and the controller are trying to load different modules viz "myPageApp" and "app.controller" and in your test with beforeEach you are trying to load 'myPageApp' module to which router is associated but not the controller.
So it seems to me that either you use same module for both router and controllers. Or try loading both modules in the test. Still I believe associating the router and controller with same module makes more sense.
An small example as below. Extract the application module in common js file (may be call it app.js)
var myApp = angular.module(
'myApp');
Now define router as
myApp.config(function ($routeProvider) {
$routeProvider
.when('/testUrl', {
templateUrl: '/myApp/views/test-view',
controller: 'TestViewController'
})
Similary define controller as
myApp.controller('TestViewController',[your dependencies goes here])
And now in your tests
beforeEach(module('myApp'));
This will work for sure. Hope it helps.

Resources