javascript - Angular UI-Router loading controller only when route is selected -
let's have 2 pages, cloud , settings. have following code set up:
var routerapp = angular.module('app', ['ui.router']); routerapp.config(function($stateprovider, $urlrouterprovider, $locationprovider) { $locationprovider.html5mode(true); $urlrouterprovider.otherwise('/cloud'); $stateprovider .state('cloud', { url: '/cloud', templateurl: 'pages/templates/cloud.html', controller: 'cloud', }) .state('settings', { url: '/settings', templateurl: 'pages/templates/settings.html', controller: 'settings' }); }); routerapp.controller('cloud', function($scope, $http, $state) { alert("cloud"); }); routerapp.controller('settings', function($scope, $http, $state) { alert("settings"); });
html
<!doctype html> <html lang="en" ng-app="app"> <head> <title>title</title> <base href="/"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.min.js"></script> <script src="/js/app.js" type="text/javascript"></script> </head> <body> <div id="navcontainer"> <a ui-sref="cloud">cloud</a> <a ui-sref="settings">settings</a> </div> <div id="pagecontent"> <div ui-view></div> </div> </body> </html>
regardless of page load, settings or cloud, each controller run no matter what. meaning 2 alerts, regardless, when reload page.
could explain need if reload website on /settings
, code in settings controller run , vice versa?
if have controllers declared in partials(views) router loading controllers fire when view loaded. sounds me need parent controller(s) fire give logic can controller both of views.
your code:
$stateprovider.state('cloud', { url: '/cloud', templateurl: 'pages/templates/cloud.html', controller: 'cloud', }) .state('settings', { url: '/settings', templateurl: 'pages/templates/settings.html', controller: 'settings' });
you setting controllers there if them share controller refer same controller so:
$stateprovider .state('cloud', { url: '/cloud', templateurl: 'pages/templates/cloud.html', controller: 'shared', }) .state('settings', { url: '/settings', templateurl: 'pages/templates/settings.html', controller: 'shared' });
Comments
Post a Comment