I'd like to know if I can put a stateprovider somewhere else than my app.js, because it causes me some problems in other pages.
app.js
var app = angular.module('myApp', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('form', {
url: '/form',
templateUrl: 'templates/step_Form/form.html?v=' + new Date().getDay()
})
// url will be nested (/form/profile)
.state('form.upload', {
url: '/upload',
templateUrl: 'templates/step_Form/form-upload.html?v=' + new Date().getDay()
})
// url will be /form/interests
.state('form.content', {
url: '/content',
templateUrl: 'templates/step_Form/form-content.html?v=' + new Date().getDay()
})
$urlRouterProvider.otherwise('/form/upload');
})
My controller
angular.module('myApp').controller('ImportGeneralCtrl', function ($scope, $stateProvider, $urlRouterProvider) {
//myfunctions
}
I integrated a multi-step form in my HTML, using the state provider.
How could i get out the state provider from app.js to only apply it on my controller?
You cant use $stateProvider or $urlRouterProvider (providers) in a controller because those providers are just made for configuration injection. It can be uses in any angular.module('myApp').config() you want but you can't user providers in a controller. In controllers you could only inject $state (modules, services, factories, e.g.):
angular.module('myApp').controller('myController', function ($scope, $state) {}
This little code snippet shows you how to create a Service, a Factory and a Provider.
Related
I treid to make a contoller for each of my page but have a broblem. Mistakes in console, and the elements of controller don`t work on html page.
I use $stateProvider cod below is the cod of config, it`s work normal.
var app = angular.module("appmyApp", ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider) {
// For any unmatched url, redirect to root
$urlRouterProvider.otherwise("/");
$stateProvider
.state('header', {
abstract: true,
templateUrl: '/app/pages/header.html'
})
.state('home', {
url: '/',
templateUrl: 'app/pages/home.html',
controller: 'HomeController'
})
}]);
When I add in the config the row - controller: 'HomeController'. I have a mistake in console.
angularjs.js:127 Error: [$controller:ctrlreg]
http://errors.angularjs.org/1.7.5/$controller/ctrlreg?p0=HomeController
at angularjs.js:7
at angularjs.js:97
at Object.<anonymous> (viewDirective.ts:410)
at angularjs.js:17
at Ba (angularjs.js:89)
at q (angularjs.js:73)
at g (angularjs.js:64)
at angularjs.js:64
at angularjs.js:69
at n (viewDirective.ts:328) "<div ui-view="" class="ng-scope">"
When I delete it, it is not any mostakes in console.
.state('home', {
url: '/',
templateUrl: 'app/pages/home.html'
})
In both case page opens good. Route is work. But controller is not work.
The cod of controller
var app = angular.module("appTradeRoom", []);
app.controller("HomeController", function ($scope) {
$scope.name = "Hello";
});
But on the view I have this.
http://prntscr.com/lzeyy5
Scripts home-controller.js I added in the head of home.html
<script src="/app/pages/home-controller.js"></script>
I added ng-controller="HomeController" to body in html page home.html but it does not work. What a problem. I Use last angularJS
Here is the reference on index.html
http://prntscr.com/lzf0cd
Change:
var app = angular.module("appTradeRoom", []);
app.controller("HomeController", function ($scope) {
To
var app = angular.module("appTradeRoom");
// ^^ no dependencies
app.controller("HomeController", function ($scope) {
When there are no dependencies angular.module() will act as a getter of existing module, otherwise it will create a new one
I am trying to make an $http call inside my publicApp.config in order to retrieve an array of available routes to match with the $urlMatcherFactoryProvider.
Right now, I am hard-coding them to be pageUrls = ['about','contact','another-page'];
But I have an url in my express API which returns an array of available URLS. The api URL is "/page-urls"
Would it be possible to make an $http.get('/page-urls') request inside the config? I know $http is available inside run(), but I need the list of available URLs BEFORE routing via the $stateProvider.
(function() {
'use strict'
var pageUrls = [];
var publicApp = angular.module('publicApp', ['ui.router'])
publicApp.config(['$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider', function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) {
pageUrls = ['about','contact','another-page'];
var urls = pageUrls.join('|');
var urlMatcher = $urlMatcherFactoryProvider.compile("/{source:(?:" + urls + ")}");
$stateProvider
.state('/', {
url: '/',
templateUrl: "views/home/home.view.html",
controller: "homeCtrl"
})
.state('urls', {
url: urlMatcher,
templateUrl: "views/pages/page.view.html",
controller: "pageCtrl"
});
$urlRouterProvider.otherwise('/');
}]);
})();
Create a provider which gets $stateProvider as an injectable. The provider will create a service that does the http request then registers the routes. Inject the service in a run block and initiate route registration.
Something like this:
var publicApp = angular.module('publicApp', ['ui.router'])
publicApp.provider('routes', function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider){
function registerRoutes(listOfUrls){
// register routes with $stateProvider
// angular.forEach(listOfUrls, function(url){
// $stateProvider.state...
// });
}
this.$get = function($http){
return {
initialize: function(){
return $http.get('/page-urls').then(function(response){
registerRoutes(response.data);
});
}
};
};
});
publicApp.run(function(routes){
routes.initialize();
});
Please consider the this code where the routeProvider is needed to inject page(n).html in ng-view.
In addition to the console error:
unknown provider: $routeProviderProvider <- $routeProvider
The argument to function routeIt is the name of the page to navigate to, How can I mix a conditional switch with routeProvider.when in order to call the page matching the argument in the most efficient manner? Thanks
(function () {
'use strict';
angular
.module('appModule')
.controller('MainMenuCtrl', ['$scope', '$http', 'TogglerFactory', '$routeProvider', MainMenuCtrl]);
function MainMenuCtrl($scope, $http, Toggler, routeProvider) {
$http.get('models/mainMenu.json').then(
function (response) {
$scope.menuItems = response.data;
},
function (error) {
alert("http error");
}
)
function routeIt (page) {
routeProvider
.when('/page1', {
url: "/page1",
templateUrl: 'views/page1.html',
controller: 'Page1Ctrl'
})
.when('/page2', {
url: "/page2",
templateUrl: 'views/page2.html',
controller: 'Page2Ctrl'
})
}
$scope.itemClicked = function (item){
Toggler.menuToggle();
routeIt(item);
}
}
})();
Service providers aren't available for injection in run phase (i.e. anywhere but provider services and config blocks). It is possible to make route provider injectable and configure it after config phase,
app.config(function ($provide, $routeProvider) {
$provide.value('$routeProvider', $routeProvider);
});
And controllers aren't the best places to implement any logic (e.g. route hot-plug).
Ok you're using your routeProvider wrong you need to configure your routes inside .config blocks
angular.module('myApp', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/page1', {
url: "/page1",
templateUrl: 'views/page1.html',
controller: 'Page1Ctrl'
}
})
If you want to change the url from your controller use $location.path('/page1'); inside your controller.
I am using $urlRouterProvider service in my app.config to define the default routes in my AngularJS application. I define it as follows:
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.when('/', '/history')
.otherwise('/history');
$stateProvider
.state('tabs', {
abstract: true,
url: '/',
template: '<my-tab></my-tab>',
onEnter: function(){console.log("enter");}
})
});
My problem is that I want to set these routes after a Boolean variable flag is fetched from database using a custom service (databaseService). If the flag is true, it should be:
$urlRouterProvider
.when('/', '/history')
.otherwise('/history');
and if flag is false, it should be:
$urlRouterProvider
.when('/', '/future')
.otherwise('/future');
How can I achieve this? I am not able to use a custom service in app.config function. Also I can't set configurations in my service because config gets set before a service is loaded. Please help!
Assuming you're going to change this once at the start of the application you could to the following (docs):
var routerProvider = null; // reference router for run phase
angular
.module('app')
.config(config)
.factory('databaseService', databaseService)
.run(run);
config.$inject = ['$urlRouterProvider'];
run.$inject = ['$urlRouter', 'databaseService'];
function config($urlRouterProvider) {
$urlRouterProvider.deferIntercept();
routerProvider = $urlRouterProvider;
}
function databaseService() {
return {
getDbFlag: function() {
// connect to db and fetch data
}
};
}
function run($urlRouter, databaseService) {
databaseService.getDbFlag()
.then(function (serviceData) {
// set the route with data from the DB
routerProvider.otherwise(serviceData.route);
$urlRouter.sync();
$urlRouter.listen();
});
}
I want to pass the data of the function PhoneList() to the UI-Router controller function to the state 'phonedescription'.
JS:
var myApp = angular.module('myApp', ["ui.router"]);
myApp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/phone")
$stateProvider
.state('phone', {
url: "/phone",
templateUrl: "index.html"
})
.state('phonedescription', {
url: "/description",
templateUrl: "description.html",
controller: function($scope){
//Want to access the angular object to pass the attributes to this controller
}
}
});
function PhoneList($scope, $http, $templateCache)
{
$scope.list = function() {
$scope.phones = //get data from backend
}
$scope.list();
};
It appears that you are defining PhoneList as a loose function outside of the angular framework. Look into using a service instead. You can then inject that service into your phonedescription controller.