angular.js - angular路由的控制器
PHP中文网
PHP中文网 2017-05-15 16:50:44
0
3
670

路由时两个页面能公用一个控制器吗,比如

javascript.state('a', { ... controller : 'aaaController' }) .state('b', { ... controller : 'aaaController' })

如果行的话,控制器是独立的作用域还是公用的,比如说我在控制器里声明了个变量i,在a页面中改变了i的值,当我路由到b页面时,i的值会跟着变吗

PHP中文网
PHP中文网

认证0级讲师

reply all (3)
伊谢尔伦

I am also learning angularjs recently. Regarding the problem mentioned by the poster, I can make a simple demonstration:

It has the following html structure, different views, and the same controller

Part of the controller code:

.controller('MyCtrl', function ($scope, $log) { $scope.num = 2; $scope.change = function () { $scope.num = 3; }; $scope.show = function () { $log.info($scope.num); }; });

First click the show button, the output result is as follows:

Then click the change to 3 button and click the show button again. The result is as follows:

It can be seen from this experiment that although it is the same controller, the scopes are actually two completely unrelated scopes.
The scope structure is also tree-shaped, corresponding to the dom structure. The above html structure will have two scopes.
Let’s look at another obvious example:

.controller('MyCtrl', function ($scope, $log) { $log.info('init scope...'); });

Look at the console

The result is printed twice, indicating that the method was executed twice. If the scope is shared, it will not be executed twice.

In summary: You declare a variable i in the controller, and change the value of i in page a. When you route to page b, the value of i will not change

hope to help you!

    我想大声告诉你

    It’s weird to use it this way, I’m not sure if it’s feasible to use it this way

    Personally I think the normal usage is:
    One page, one controller
    If you need to share variables and methods between controllers, you can build a service in angular to store the variables and methods. In different controllers, just inject the service we wrote

    The official document also clearly states that service is used to share code:
    Services
    Angular services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app.

    https://docs.angularjs.org/guide/services

      伊谢尔伦

      After switching the route, the life cycle of the controller is over, and the current$scopeand sub-scopes are dead.
      If you need to share data between multiple controllers, you can use services.

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!