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>
Related
I basically need to call a server that's will return me a JSON structure before load the controller.
I was using many methods to archive that, but it's not working. It's don't show me any error and the page got blank. Any clue about what's going on ?
This is my controller..
angular
.module('app',[
'ngAnimate',
'ui.router',
'ui.bootstrap',
'ngCookies'
])
.run(function($rootScope) {
$rootScope.backendServer = "http://localhost:5000/";
})
.config(['$urlRouterProvider','$stateProvider', function($urlRouterProvider,$stateProvider) {
$stateProvider
.state('cms',{
url: '/my',
templateUrl: './app/templates/my.html',
controller : 'my',
resolve: {
dbState: function ($q) {
var defer = $q.defer();
Database.check().then(function (s) {
defer.resolve(s);
});
return defer.promise;
}
}
})
}])
.controller(function ($scope){
})
...and this is my service:
angular
.module('app')
.factory('Database',['$http', '$rootScope','$q', function($http, $rootScope, $q) {
return {
check: function () {
var call = $rootScope.backendServer + 'cms/database/check';
return $http.get(call);
}
}
}]);
don't create a defer object when you already returning a promise. so remove the defer and just return the factory function
also, inject the Database service to resolve
resolve: {
dbState: function(Database) {
return Database.check()
}
}
In the controller catch it like this
.controller("ctrl", function($scope, dbState) {
console.log(dbState.data)
})
Demo
I'm adding route authentication to my angular app.
For some reason when I try to navigate to the logentries view, I cannot get the code in the resolve function to execute.
I've added a breakpoint using Chrome developer tools, but it doesn't get hit.
The view does get loaded, however.
I thought the resolve would get hit before the controller is instantiated and the view rendered.
Why isn't it?
(function () {
'use strict';
angular.module('app')
.config(appConfig)
.run(routeAuthentication);
routeAuthentication.$inject = ['$rootScope', '$location'];
function routeAuthentication($rootScope, $location) {
$rootScope.$on('$routeChangeError', function (event, current, previous, rejection) {
if (rejection === 'Not Authenticated') {
console.log('Not Authenticated for Route');
$location.path('/');
}
});
}
appConfig.$inject = ['$routeProvider'];
function appConfig($routeProvider) {
$routeProvider
.when("/logentries", {
templateUrl: "app/views/logEntries.html",
controller: "logEntries",
resolve: function ($q, $location) {
// Code not entering here as far as I can tell.
var deferred = $q.defer();
deferred.resolve();
if (true) { // TODO - use authenticationServce
$location.path('/login');
}
return deferred.promise;
}
})
// other routes
};
})();
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'm trying to to use the Angular UI Bootstrap module, in specific the Modal plugin.
My app-folder is structured in this way:
app
scheda
scheda.html
schedacontroller.js
app.js
css
...
index.html
This is app.js, the main app file:
// created the module GasistaFelice
// also included ngRoute for all our routing needs
angular.module('ngGasistaFelice', [])
.run(function($rootScope) {
$rootScope.gasID = "10"; //default value
});
angular.module('ngGasistaFelice', ['ui.bootstrap']);
var GasistaFelice = angular.module('ngGasistaFelice', ['ngRoute']);
GasistaFelice.config(['$routeProvider',function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'app/ordinare/ordinare.html',
controller : 'orderController'
})
// route for the paniere page
.when('/:id/gasmember/:id/basket', {
templateUrl : 'app/paniere/paniere.html',
controller : 'paniereController'
})
// route for the scheda page
.when('/:id/profile', {
templateUrl : 'app/scheda/scheda.html',
controller : 'schedaController'
})
// route for the conto page
.when('/:id/gasmember/:id/cash', {
templateUrl : 'app/conto/conto.html',
controller : 'contoController'
})
.otherwise({
redirectTo: '/'
});
}]);
exc....
This is the controller of the page in which i want to put the Modal plugin:
var app = angular.module('ngGasistaFelice', ['ui.bootstrap']);
app.controller('schedaController', function ($scope, $routeParams, $modal, $log, $http) {
var id = $routeParams.id;
// --- URL finale ---
//var url = 'http://localhost:8000/gasistafelice/api/v1/person/id/?format=json';
//URL di prova
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
When i load the page containing the schedaController, i keep getting this error:
Error: [$injector:unpr] h ttp://errors.angularjs.org/1.2.16/$injector/unpr?p0=%24routeParamsProvider%20%3C-%20%24routeParams
at Error (native)
at http://localhost/GasistaFelice2_angular/js/angular.min.js:6:450
at http://localhost/GasistaFelice2_angular/js/angular.min.js:35:431
at Object.c [as get] (http://localhost/GasistaFelice2_angular/js/angular.min.js:34:13)
at http://localhost/GasistaFelice2_angular/js/angular.min.js:35:499
at c (http://localhost/GasistaFelice2_angular/js/angular.min.js:34:13)
at d (http://localhost/GasistaFelice2_angular/js/angular.min.js:34:230)
at Object.instantiate (http://localhost/GasistaFelice2_angular/js/angular.min.js:34:394)
at http://localhost/GasistaFelice2_angular/js/angular.min.js:66:112
at http://localhost/GasistaFelice2_angular/js/angular.min.js:53:14
Thank you
You're defining angular.module('ngGasistaFelice', []) multiple times with different required modules (inside of the second parameter to the module function):
angular.module('ngGasistaFelice', [])
angular.module('ngGasistaFelice', ['ui.bootstrap']);
var GasistaFelice = angular.module('ngGasistaFelice', ['ngRoute']);
var app = angular.module('ngGasistaFelice', ['ui.bootstrap']);
...specifically, the last one is the one you're trying to use ngRoute with, and you haven't even injected it there.
A better solution is to define it once, say:
var GasistaFelice = angular.module('ngGasistaFelice', [
'ui.bootstrap',
'ngRoute'
]);
And then you could do what you were trying to do:
GasistaFelice.controller(...);
Or, if you need this in another file (or scope) and GasistaFelice is not yet defined, you can get it by calling angular.module without passing the required dependencies, like:
var app = angular.module('ngGaistaFelice');
app.controller(...);
Since version 0.14.0 angular team prefixed all components you have to use, look more. For your case you need
Change: $modal for $uibModal.
Change: $modalInstance for $uibModalInstance.
Change: modal-transclude for uib-modal-transclude
I have a simple resolve function set up in my route provider. Something like
.config(['$routeProvider', 'Constants', function config($routeProvider, Constants) {
$routeProvider.
when('mypage', {
templateUrl: 'partials/mypage.tpl.html',
controller: 'MyPageCtrl',
reloadOnSearch: false,
resolve: {
factory: 'MyPageResolve'
}
})
)];
Where that factory is declared in a module like this:
.factory('MyPageResolve', ['$q', '$log', 'someAPI',
function ($q, $log, someAPI) {
var defer = $q.defer();
var postUserFunc = function () {
someAPI.get(
function(data, status) { //$http.get().success() func
defer.resolve();
}
);
};
return defer.promise;
}]);
What's happening is on straight refresh or on the first load, this resolve method is hit. However, if I have a $location.url('/mypage'); change from one route to this one, angular is not re-resolving this controller.
I might be not thinking of resolve in the right way, and if so, would take recommendations on the 'angular' way to do this. I would like all this information loaded before the view, and is variable based on the route params.
Ends up I needed to make that factory into just a function. A factory acts as a singleton, so it will only run once.
So I made my factory look like:
var myPageResolve = ['$q', '$log', 'someAPI',
function ($q, $log, someAPI) {
var defer = $q.defer();
var postUserFunc = function () {
someAPI.get(
function(data, status) { //$http.get().success() func
defer.resolve();
}
);
};
return defer.promise;
}]);
And instead of resolving on 'myPageResolve', I resolved on myPageResolve. Very subtle change made all the difference.