search

Home  >  Q&A  >  body text

angular.js - How to inject data into $rootScope when developing with Angular

In addition, is there a js similar to main.js in which global variables can be defined? For example, var http = "www.xxxx.com/" can make other Ctrl.js callable.

PHP中文网PHP中文网2828 days ago649

reply all(5)I'll reply

  • 高洛峰

    高洛峰2017-05-15 16:55:43

    The idea is wrong, angular中不需要定义全局变量。你的数据应该通过service, factory, providerwill provide it.
    And these things can be dependency injected, so there is no need for global variables at all

    reply
    0
  • PHPz

    PHPz2017-05-15 16:55:43

    $rootScope is an object and can be bound to global variables in the form of $rootScope.xxx='';

    reply
    0
  • 某草草

    某草草2017-05-15 16:55:43

    @leftstick is right, AngularJS uses dependency injection style to structure the entire application framework. It is best not to declare global variables, but to make it a Service. This way you can avoid a lot of problems:

    1. Naming conflict. Naming conflicts in JavaScript will not give any warning. If your project is small, the probability of occurrence is small, but it is very difficult to debug.
    2. Initialization sequence. If you get execution before ACtrl中定义了一个全局变量window.a,比如你想在BCtrl中使用它,那么你需要保证ACtrlBCtrl, this is often difficult to implement and even logically confusing.

    In Angular, the most reasonable way is to put a做成一个aService,注入到ACtrlBCtrl inside.

    How to define a service and the relationship between Module, Service, Factory and Provider can refer to this blog:

    http://harttle.github.io/2015/06/07/angular-module.html

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-15 16:55:43

    angular.module('app', []).run(function($rootScope) {
        $rootScope.http = 'www.xxxx.com/';
    });
    

    reply
    0
  • 怪我咯

    怪我咯2017-05-15 16:55:43

    Now angularjs2 is out

    reply
    0
  • Cancelreply