我一直在尝试使用 AngularJS,我不得不说谷歌已经超越了自己。我的意思是,数据操作是轻而易举的,而且 Angular 也不是很难学。现在,我只是在浏览 Angular 的源代码。
当我想更改默认 {{}}
时,我出于必要开始这样做。 mustache 到别的东西上,因为我和 django 一起工作。
现在,我想做点别的,也就是如何在 AngularJS View 的 javaScript 中更改 Controller 的默认名称。我知道这听起来有点令人困惑,所以让我用一个例子来解释一下:
<html ng-app>
<div ng-controller="Controller">
<input type="text" ng-model="name">
<h1>{{ name }}</h1>
<h1> {{ age }}</h1>
</div>
<script>
var Controller = function ($scope) {
$scope.name = "Happy Person";
$scope.age = "30";
};
</script>
</html>
现在,如您所见,如果您将 ng-controller
命名为作为Controller
,那么你必须给你的 Controller 命名。这很好,但我想要的是,对于每个名字,都应该预先添加一些东西。例如,在本例中,ng-controller
叫做Controller
,没关系,我想让 Angular 做的是搜索 ang_<controller name>
反而。因此,例如,在这种情况下,angular 将搜索 ang_Controller
而不是 Controller
.
您将如何实现这一目标,您将更改代码的哪些部分?这似乎是一件愚蠢的事情,但我想这样做是为了更好地理解 Angular 源代码的工作原理,以及如何按照我的喜好操作它。
最佳答案
首先,如果困扰您的是使用全局变量,请注意您根本没有被迫这样做。对于大型应用程序,最好使用 controller()
方法(如 documentation 所建议):
angular
.module('MyModule')
.controller(
'MyController',
[
'$scope',
function ($scope) {
// ...
}
]
);
无论如何,恕我直言,最好的方法是创建您自己的指令,例如 prependingController
。它的唯一目标是定义经典的 ngController
指令,但带有正确的前缀。当然,您将为此使用 AngularJS 常量 (documentation):
angular
.module('MyModule')
.directive(
'prependingController',
[
'CONTROLLER_PREFIX',
'$compile',
function (CONTROLLER_PREFIX, $compile) {
return {
link : function ($scope, element) {
element
.attr(
'ng-controller',
CONTROLLER_PREFIX + element.attr('prepending-controller')
)
.removeAttr('prepending-controller');
$compile(element)($scope);
},
};
}
]
);
关于javascript - 在 angularjs Controller 的默认名称前加上一个名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17999382/