你如何使用Angular Js声明一个全局变量?

时间:2015-07-30 12:15:47

标签: angularjs

我想要一个可以在所有控制器中使用但不想为它创建服务的变量。是否可以在角度js中使用?

3 个答案:

答案 0 :(得分:30)

您可以使用constants or values

<强>常量

        Rect bounds = new Rect(x1, y1, x2, y2);// set the bounds
        String textOnCanvas = "text to be wriiten";
        StaticLayout sl = new StaticLayout(textOnCanvas, textPaint,
                bounds.width(), Layout.Alignment.ALIGN_CENTER, 1, 1, true);
        canvas.save();
        float textHeight = getTextHeight(textOnCanvas, textPaint);
        int numberOfTextLines = sl.getLineCount();
        float textYCoordinate = bounds.exactCenterY() -
                ((numberOfTextLines * textHeight) / 2);

        //text will be drawn from left
        float textXCoordinate = bounds.left;
        canvas.translate(textXCoordinate, textYCoordinate);
        //draws static layout on canvas
        sl.draw(canvas);
        canvas.restore();

<强>值

var app = angular.module('myApp', []);
app.constant('appName', 'Application Name');

app.controller('TestCtrl', ['appName', function TestCtrl(appName) {
    console.log(appName);
}]);

http://ilikekillnerds.com/2014/11/constants-values-global-variables-in-angularjs-the-right-way/

答案 1 :(得分:10)

使用value()定义对象,并存储您的全局变量&#39;作为该对象的属性。然后将该对象作为依赖项添加到需要访问其属性的任何控制器。这具有将所有变量封装到单个对象中的积极副作用,该对象整齐且不太可能遭受命名空间冲突。

以下是模式:

app.value('myVars', {
    usersOnline:0
});
app.controller('TestCtrl', ['myVars', function TestCtrl(myVars) {
    console.log(myVars.usersOnline);
    myVars.usersOnline = 15;
    console.log(myVars.usersOnline);
}]);

仅供参考Aseem的答案不会奏效,因为他的例子使用value()原始类型。要明确什么不起作用:

app.value('usersOnline', 0);
app.controller('TestCtrl', ['usersOnline', function TestCtrl(usersOnline) {
    console.log(usersOnline);
    usersOnline = 15; // <-- THIS WILL NOT PERSIST outside the controller.
    console.log(usersOnline);
}]);

答案 2 :(得分:3)

您可以在$ rootScope上设置该变量。并将$ rootScope注入将使用全局的控制器。

相关问题