使用没有值的 ng-app [英] Using ng-app without a value

查看:25
本文介绍了使用没有值的 ng-app的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,您会在页面上看到 Angular 使用 ng-app="myModule" 之类的指令进行初始化,但仅使用 ng-app 也是有效的.然而,由于像控制器这样的东西是用 myModule 注册的,所以只使用 ng-app 有什么用吗?如果您没有为 ng-app="..." 指定模块,有没有办法注册控制器等?

解决方案

在 Angular 1.3 之前(当您可以在全局范围内定义控制器时),Angular 能够自动发现全局定义的控制器.

从 Angular 1.3 开始,所有控制器都必须在一个模块中定义,因此,您从没有模块的 ng-app 中获得的功能非常有限.它可能有利于原型设计,但即便如此,您也不会得到太多.

所以,pre angular 1.3 用法:

<div ng-controller="SomeController">{{某物}}

你可以像这样定义你的javascript,它会起作用:

如评论中所述,您仍然可以使用 $controllerProvider.allowGlobals() 启用此行为.也就是说,Angular 团队从一开始就试图阻止我们以这种方式定义控制器,应该避免:

<块引用>

注意:虽然 Angular 允许您在全局范围内创建控制器函数,但不推荐这样做.在实际应用程序中,您应该为应用程序使用 Angular 模块的 .controller 方法 [...]

Usually, you see Angular initialized on a page with a directive like ng-app="myModule", but it is valid to just use ng-app. However, as things like controllers are registered with myModule, is it ever useful at all to just use ng-app? Is there a way to register controllers etc. if you don't specify a module to ng-app="..."?

解决方案

Prior to Angular 1.3 (when you could define controllers on the global scope), Angular was able to automatically discover controllers that were defined globally.

As of Angular 1.3, all controllers have to be defined within a module, and thus, you'd get very limited functionality out of an ng-app without a module. It could potentially be beneficial for prototyping, but even there, you're not going to get much.

So, pre-angular 1.3 usage:

<div ng-app>
   <div ng-controller="SomeController">
       {{something}}
   </div>
</div>

You could define your javascript like this and it would work:

<script>
    function SomeController($scope) {
        $scope.something = "Hello";
    }
</script>

Edit:

As mentioned in the comments, you can still enable this behavior by using $controllerProvider.allowGlobals(). That said, the Angular team has tried to deter us from defining controllers this way from the start, and should be avoided:

NOTE: Although Angular allows you to create Controller functions in the global scope, this is not recommended. In a real application you should use the .controller method of your Angular Module for your application [...]

这篇关于使用没有值的 ng-app的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆