Angular UI-Router boot controller only when choosing a route

Say I have two pages, a cloud and settings . I have the following code installed:

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>

No matter which page I load, settings or the cloud, each controller will work no matter what. Value I receive 2 warnings, regardless of when I reload the page.

Can someone explain what I need to do so that if I reload my site on /settings, only the code in my settings controller will work and vice versa?

+4
source share
1 answer

, (), , . , (), , , .

:

$stateProvider.state('cloud', {
            url: '/cloud',
            templateUrl: 'pages/templates/cloud.html',
            controller: 'cloud',
        })

        .state('settings', {
            url: '/settings',
            templateUrl: 'pages/templates/settings.html',
            controller: 'settings'  
        });

, , , :

$stateProvider

    .state('cloud', {
        url: '/cloud',
        templateUrl: 'pages/templates/cloud.html',
        controller: 'shared',
    })

    .state('settings', {
        url: '/settings',
        templateUrl: 'pages/templates/settings.html',
        controller: 'shared'  
    });
+1

Source: https://habr.com/ru/post/1584665/


All Articles