gpt4 book ai didi

javascript - 如何在 View 中使用 Angular 常量?

转载 作者:行者123 更新时间:2023-11-29 10:40:32 24 4
gpt4 key购买 nike

我试图从我的 View 中的 Angular Directive(指令)中删除大量字符串文字值。我有一个常量的开头,我希望使它成为全局常量,例如:

// UI Validation constants.
MyAngularApp.constant('valid', {
"postalCode": {
"pattern": "/^[0-9]+$/",
"minLength": 4
}
});

然后我想在我的 View 模板的输入指令中使用这个常量,方式类似于:

<input type="text" ng-pattern="{{valid.postalCode.pattern}}" blah blah>

但在这里我对指令参数内的绑定(bind)有严重的怀疑。

我看到了一些将这样一个常量添加到根作用域的建议,但也看到了一些避免根作用域并且只将其添加到 Controller 内的本地作用域的建议,但这将涉及对多个 Controller 的代码更改,我更愿意这样做只是一个变化。

如果我决定使用根作用域,我将如何添加这个常量?我对此的错误尝试是:

console.log("Abandon all hope who enter here!");
MyAngularApp.config(function ($rootScope) {
$rootScope.valid = valid; // How to access the constant here?
});

但是这段代码给我错误:

Uncaught Error: [$injector:modulerr]

已添加:下面的一些建议涉及 Angular run 函数,但我找不到它。 module 调用是这样的:

var MyAngularApp = angular.module('MlamAngularApp', ['kendo.directives', 'ngRoute', 'ui.bootstrap', 'ngReallyClickModule', 'ngMessages', 'angular-loading-bar', 'ngAnimate']);

最佳答案

根据 OP - 如果您想在应用加载时绑定(bind)到 rootScope,您可以使用这样的运行 block :

app.run(function($rootScope) {
$rootScope.name = 'bound during run'
})

我更新了演示作用域继承的 plunker 以展示它的实际效果。

Plunker

在 $rootScope 中存储东西是不好的做法。这是一个例子,为什么:

$scope inheritance

它会使事情变得困惑和困惑,尤其是当多人维护代码时。您将某些内容绑定(bind)到 rootScope,并且每个 Controller 的范围都有该属性附加到它的范围。如果您必须这样做,您应该非常清楚地记录下来。

这样做:

app.constant('myConstant', {
"postalCode": {
"pattern": "/^[0-9]+$/",
"minLength": 4
}

})

只要在你需要的地方注入(inject):

app.controller('MainCtrl', function($scope, myConstant) {
$scope.name = myConstant;
});

Banner 的方法也很好,尽管我认为这样做可以更好地保持高层次的抽象,而不是像那样将一堆东西附加到模块上。通过这种方式,您可以将所有常量放入 constants.js 或其他任何内容中,并保持一切清洁。

关于javascript - 如何在 View 中使用 Angular 常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30160778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com