angular.js - 在使用Angular开发中如何将数据注入$rootScope
PHP中文网
PHP中文网 2017-05-15 16:53:43
0
5
601

另外,是否有类似于main.js的那种js,里面可以去定义全局变量。例如var http = "www.xxxx.com/",可以使得其他的Ctrl.js,都可以调用。

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
小葫芦

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

PHPzhong

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

某草草

@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

我想大声告诉你
angular.module('app', []).run(function($rootScope) {
    $rootScope.http = 'www.xxxx.com/';
});
刘奇

Now angularjs2 is out

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template