javascript - 在 angularjs Controller 的默认名称前加上一个名称

标签 javascript angularjs

我一直在尝试使用 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);
                    },
                };
            }
        ]
    );

Fiddle

关于javascript - 在 angularjs Controller 的默认名称前加上一个名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17999382/

相关文章:

javascript - keyup函数的Javascript问题-尝试多次使用页面上的同一表单域,但只有第一个表单域有效

javascript - 如何将数据发送到 PHP 脚本并使用 jQuery AJAX load() 指令

javascript - 离线使用 Firebase Angular 应用程序

javascript - AngularJS:遍历单选按钮组

angularjs - 在 Angularjs 中添加/删除路由更改的 CSS 类

javascript - AngularJS 中 ( $scope.something || 0) 的含义是什么

javascript - 如何在 moment.js 中获取之前的确切日期?

javascript - 网络冒险游戏中叙述的滚动文本

javascript - 如何使用其他集合的子数组数据过滤来自mongo集合子数组的数据

angularjs - 总是在后台运行 Gulp