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]);
Related
I have tried creating a controller using meanjs.org. The controller is working fine with the other existing controllers but it is not working fine with new one I have created, Help would be appreciated, Thank you.
angular.js:12808 Error: [ng:areq] Argument
'TestownerControllerController' is not a function, got undefined
http://errors.angularjs.org/1.4.14/ng/areq?p0=TestownerControllerController&p1=not%20aNaNunction%2C%20got%20undefined
this is my controller code
(function() {
'use strict';
angular.module('users').controller('TestownerControllerController', TestownerControllerController);
TestownerControllerController.$inject = ['$scope'];
function TestownerControllerController($scope) {
var vm = this;
// Testowner controller controller logic
// ...
init();
function init() {
}
}
})();
In your case you miss [] where you define user app angular.module('users')...
[]: it's required and we use it to inject other modules.
also you can set a config in your app like this:
app.config(["$controllerProvider", "$compileProvider", "$filterProvider", "$provide", function ($stateProvider, configs, $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;
}]);
This config help you to register a module with others dependencies.
//our main app
var app = angular.module('users', [])
//our controller
function testController($scope) {
function init() {
//somthing
}
init();
}
testController.$inject = ['$scope'];
app.controller('testController', testController);
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 ?
I am doing project in angularjs,my requirement is need to pass value from one different app module controller to another app module service using $rootScope
Here my part of code
Login module and controller
var loginApp = angular.module('loginApp', [ 'ngCookies' ]);
loginApp.controller('loginCtrl', function($scope, $cookies, $cookieStore,
$rootScope) {
$scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
$rootScope.loggedInUser = $scope.name;
window.location = "pages/index.html";
} else
alert('User / Password Invalid');
}
});
here my app.js file
I injected the login module to another module
var smartCities = angular.module('smartCities', [ 'ngRoute', 'ngAnimate',
'ui.bootstrap', 'ngTouch', 'ui.grid.exporter', 'ui.grid',
'ui.grid.selection', 'ui.grid.autoResize', 'ngCookies', 'loginApp' ]);
below i access the loggedInuser here
smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log($rootScope.loggedInUser);
$location.path(next.$$route.originalPath);
});
});
but in console i am getting message like
undifined
please tell me where i did wrong
you can use localstorage or sessionstorage for this purpose.
login Controller :
loginApp.controller('loginCtrl', function($scope, $cookies, $cookieStore,
$rootScope) {
$scope.redirect = function() {
if ($scope.name == 'admin' && $scope.password == 'admin') {
localStorage.loggedInUser = $scope.name;
window.location = "pages/index.html";
} else
alert('User / Password Invalid');
}
loggedin user :
smartCities.run(function($rootScope, $location, $cookies, $cookies,
$cookieStore) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log(localStorage.loggedInUser);
$location.path(next.$$route.originalPath);
});
Here is the Doc Link: https://docs.angularjs.org/api/ng/type/angular.Module#value
//this is one module
var myUtilModule = angular.module("myUtilModule", []);
// this is value to be shared among modules, it can be any value
myUtilModule.value ("myValue" , "12345");
//this is another module
var myOtherModule = angular.module("myOtherModule", ['myUtilModule']);
myOtherModule.controller("MyController", function($scope, myValue) {
// myValue of first module is available here
}
myOtherModule.factory("myFactory", function(myValue) {
return "a value: " + myValue;
});
Hope It Helps!
The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});
I am trying to lazy load my controllers in angular via requirejs
.when('/', {
templateUrl: 'views/main.html',
resolve: {
load: ['$q', '$rootScope', function ($q, $rootScope) {
var deferred = $q.defer();
// At this point, use whatever mechanism you want
// in order to lazy load dependencies. e.g. require.js
// In this case, "itemsController" won't be loaded
// until the user hits the '/items' route
require(['controllers/main'], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
});
This is my controller
define(['angular'], function (angular) {
'use strict';
var app = angular.module('someApp.controllers.MainCtrl', [])
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.abc = "abc";
return app;
});
My view doesnt show the variable abc. Even though the view is rendering fine
<span>abc={{abc}}</span>