I am trying to create a factory that loads the html template and then compile the html with the newly loaded controller...
app.factory('$modal', function ($templateProvider, $compile, $ocLazyLoad){
return {
open: function(modal) {
$ocLazyLoad.load([
'modals/'+modal+'.html',
'modals/'+modal+'.ctrl.js',
]).then(function() {
// How ?
})
}
}
});
I also tried to get the html via $templateProvider after loading the controller with ocLazyLoad and then using the $compile service. The problem beeing at any time that the controller is not available !
In the config, I tried the following:
app.config(['$stateProvider', '$httpProvider', '$locationProvider', '$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$ocLazyLoadProvider',
function ($stateProvider, $httpProvider, $locationProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $ocLazyLoadProvider) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
app.value = $provide.value;
}]);
The idea being that I should be able to declare a new controller that just got loaded by using angular.module('myApp').controller(.... No success either.
I am stuck at this point, has anyone done that before ?
Related
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.
This is my Angularjs .config file that opens lead.html page whenever 'tasks' is activated from another html using ui-router.
App
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$stateProvider
.state('tasks', {
templateUrl: {{name}}.html,
controller:"TasksController"
});
}]);
This is my Taskscontroller.js
App
.controller(
"TasksController", [function($scope, $http,$window) {
var self = this;
self.name = 'lead'; // I wanna use this parameter in templateUrl
console.log("In tasks Controller");
}]);
I want to make the templateUrl take parameter from TasksController so that it redirects to relevant page based on the parameter set in TasksController.
Please guide me how to do this.
Thanks
You could try using $stateParams:
App.config(['$stateProvider', '$urlRouterProvider', '$stateParams', function($stateProvider, $urlRouterProvider, $stateParams) {
$stateProvider
.state('tasks', {
params: {
page: null
},
templateUrl: {{$stateParams.page}}.html,
controller: "TasksController"
});
}]);
Then in your controller:
App.controller("TasksController", [function($scope, $http, $window, $stateParams, $state) {
var self = this;
self.$stateParams.page = 'some_url.html';
self.$state.go('tasks');
}]);
Don't forget the injection in the controller too. Haven't tested this but you may need the $state go like this:
self.$state.go('tasks', { page: 'some_url.html' }, { });
I try to do a demo of charts. I get uncaught modulerr. I am not able to solve this issue. Please let me know where I am wrong.
Note :
I have run bower install and I have the libraries injected to the module under /public/lib folder.
My index.jade
doctype html
html(lang='en', xmlns='http://www.w3.org/1999/xhtml', xmlns:fb='https://www.facebook.com/2008/fbml', itemscope='itemscope', itemtype='http://schema.org/Product')
head
block header
block stylesheet
link(rel='stylesheet', href='/semantic/semantic.min.css')
link(rel='stylesheet', href='/css/vendor.min.css')
block headerscript
script(type='text/javascript', src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js")
script(type='text/javascript', src='//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js')
script(type='text/javascript', src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js')
body(ng-init="compare='hellovar'")
.ui.grid
.ui.computer.tablet.only.fitted.row
.column
.ui.menu
.item
a.ui.green.button(href="/")
| Chart Demo
.ui.mobile.only.three.column.inverted.black.fitted.row
.column.floated.left.inverted
.ui.menu.fluid.two.item.inverted
header.item
a.ui.green.icon.button(href="/")
i.content.icon
.column
| Alasql Demo
.column.right.aligned
.fitted.row
.column
block content
div(ui-view)
block footer
script(type='text/javascript').
angular.element(document).ready(function() {
angular.bootstrap(document, ['home.core']);
});
My controller part
'use strict';
angular.module('home.core',['ngRoute']);
angular.module('home.core')
.controller('home.core.controller', ['$rootScope', '$scope', '$window',
function($rootScope, $scope, $window) {
console.log("inside home core controller");
function _init() {
console.log("Inside Home Controller");
}
_init();
}
]);
angular.module('home.core')
.config(
["$stateProvider", "$urlRouterProvider",
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state("home-core", {
url: '/',
templateUrl: 'partials/home/core/index.html',
controller : 'home.core.controller'
});
}
]);
angular.module('home.core')
.factory('home.core.service', ['Restangular',
function(Restangular) {
var restAngular = Restangular.withConfig(function(Configurer) {
Configurer.setBaseUrl('/api/ecommerce');
});
return {
create: restAngular.all('')
.post
}
}
]);
I get the below error when I run the web app
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=home.core&p1=Error…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.15%2Fangular.min.js%3A17%3A381
Firstly, I don't see where you are running the restangular script:
<script src="js/lib/restangular.min.js"></script>
Second, is all of your Angular code in one file? You first have to inject restangular into your main module. Can you try changing your code to this:
'use strict';
angular.module('home.core',['ngRoute','restangular'])
.controller('home.core.controller', ['$rootScope', '$scope', '$window',
function($rootScope, $scope, $window) {
console.log("inside home core controller");
function _init() {
console.log("Inside Home Controller");
}
_init();
}
])
.config(
['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state("home-core", {
url: '/',
templateUrl: 'partials/home/core/index.html',
controller : 'home.core.controller'
});
}
])
.factory('home.core.service', ['Restangular',
function(Restangular) {
var restAngular = Restangular.withConfig(function(Configurer) {
Configurer.setBaseUrl('/api/ecommerce');
});
return {
create: restAngular.all('')
.post
}
}
])
i am using angle theme with Angular for my project and i am doing unit testing on this using jasmine framework. But when i run the test cases, it gives error of "Argument 'controller' is not a function, got undefined". here is my test.js file....
describe('registrationController',function(){
beforeEach(module('appTesting'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
it('Check Working Or Not', function() {
var $scope = {};
var controller = $controller('registrationController', { $scope: $scope });
$scope.password = 'passwordlength';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
Error -
Error: [ng:areq] Argument 'registrationController' is not a function, got undefined http://errors.angularjs.org/1.3.10/ng/areq?p0=registrationController&p1=not%20a%20function%2C%20got%20undefined
No i am using karma to run jasmine.
I am defining my module here
var App = angular.module('appTesting', ['ngRoute', 'ngAnimate', 'ngStorage', 'ngCookies', 'pascalprecht.translate', 'ui.bootstrap', 'ui.router', 'oc.lazyLoad', 'cfp.loadingBar', 'ngSanitize', 'ngResource'])
.run(["$rootScope", "$state", "$stateParams", '$window', '$templateCache', function ($rootScope, $state, $stateParams, $window, $templateCache, $location) {
// Set reference to access them from any scope
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.$storage = $window.localStorage;
}
]);
App.config(['$stateProvider','$urlRouterProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$ocLazyLoadProvider', 'APP_REQUIRES', 'RouteHelpersProvider',
function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $ocLazyLoadProvider, appRequires, helper) {
'use strict';
App.controller = $controllerProvider.register;
App.directive = $compileProvider.directive;
App.filter = $filterProvider.register;
App.factory = $provide.factory;
App.service = $provide.service;
App.constant = $provide.constant;
App.value = $provide.value;
$stateProvider
.state('app.registrationState', {
url: '/registration',
title: 'Ragistration Page',
templateUrl: helper.basepath('registrationPage.html'),
resolve: helper.resolveFor('registrationController','angularFileUpload')
})
}])
.controller('NullController', function() {});
App.constant('APP_REQUIRES', {
scripts:
{
'registrationController' :['app/js/registrationcontroller.js'],
}
});
Angular
Can the controller be found?
Do you have a controller named registrationController?
Is it in a module named appTesting?
You should have the following code somewhere in your app:
angular.module("appTesting").controller("registrationController", ...);
Karma
If you are using Karma-jasmine:
Did you include the file where you define the controller (registration-controller.js) in your karma.conf.js?
karma.conf.js
module.exports = function(config) {config.set({
files : [
'src/registration-controller.js',
...
],
...
});};
Jasmine
If you're not using Karma to run Jasmine, I'm assuming you're using the Jasmine test runner (HTML file). In that case:
Did you include the controller in the HTML file?
You need to include the controller's script:
<head>
...
<script type="text/javascript" src="src/registration-controller.js"></script>
...
</head>
Either the controller cannot be found or was not created due to error on the source code where controller was defined.
In my case, it was due to a statement that had error which affected succeeding lines of code cause the controller to be not loaded.
This can happen due to variety of reasons.
-> controller name is not referenced right
-> controller is not created due to some error.
In my case, I had the controller name mismatched in
directive:
.controller('IAddController', AddController)
Jasmine spec.ts:
// Instantiate controller
addController= $controller<any>('AddController', {*
I am using this tutorial to create lazy loading:
http://ify.io/lazy-loading-in-angularjs/
And this tutorial for authentication:
https://coderwall.com/p/f6brkg
I wanted to save the authentication service in a different file, say AuthenticationService.js and inject it as a dependency into my app.js. However, the app.js has to be bootstrapped, and returned before I can use the define(['app'], function(){ ... } for the service.
How can I accomplish this?
What I have so far:
app.js
define(
[
'app/scripts/routes',
'app/scripts/services/dependencyResolverFor',
'app/scripts/services/AuthenticationService',
'uiRouter'
],
function(config, dependencyResolverFor, AuthenticationService)
{
var app = angular.module('app', ['ngRoute','ui.router']);
console.log(AuthenticationService);
// Register all providers. We can now lazy load files as needed.
// Provide dependencies through the routes.js
app.config([
'$routeProvider',
'$locationProvider',
'$controllerProvider',
'$compileProvider',
'$filterProvider',
'$provide',
'$stateProvider',
function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $stateProvider) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
$locationProvider.html5Mode(false);
if(config.routes !== undefined) {
angular.forEach(config.routes, function(route, path) {
// Routing happens here
});
}
}
]);
// Check User
app.run( ['$rootScope', '$state', function( $rootScope, $state) {
$rootScope.$on("$stateChangeStart", function(event, currentRoute, prevRoute){
// Authenticate here and have access to the service
});
}]);
return app;
});
AuthenticationService.js (want it to be like this. Currently, it doesn't work because it says app is not defined, since it is not returned yet within app.js
define(['app'], function(app)
{
app.service('AuthenticationService', function(){
var isLogged = false;
var user = 'guest';
var username = '';
this.login = function() { isLogged = true; };
this.checkLogin = function() { return isLogged; };
});
});
You could put your AuthenticationService in a separate angular module, then make your main app depend on the sub-module (i.e. the module on which AuthenticationService is defined). something like...
angular.module('OtherModule', []).service('AuthenticationService', /* etc */);
then include the module:
var app = angular.module('app', ['ngRoute','ui.router', 'OtherModule']);
edit: you can call .name on a module object (for example, the one getting injected into app.js) to get it's name, so you don't have to hard-code the 'OtherModule' string as a dependency, you can do something like
var app = angular.module('app', ['ngRoute','ui.router', InjectedModule.name]);