ng-controller 指令和路由中的控制器有什么区别? [英] What is the difference between an ng-controller directive and a controller in the route?

查看:22
本文介绍了ng-controller 指令和路由中的控制器有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完成了 AngularJS 网站上的教程,我注意到在 第 7 步,它们改变了将控制器引入应用程序的方式.最初,他们使用一个指令:

I worked through the tutorial on the AngularJS website and I noticed that in at step 7, they change how a controller is introduced into the application. Initially, they use a directive:

<body ng-controller="PhoneListCtrl">
...
</body>

但是,它后来更改为使用 controller 属性作为 ng-route 的一部分.

However, it later gets changed to use a controller attribute as part of an ng-route.

$routeProvider.
    when('/phones', {
        templateUrl: 'partials/phone-list.html',
        controller: 'PhoneListCtrl'
    }). 
    /* rest of routes here */ 

这是进行更改的 git diff.这两种技术有区别吗?

Here's the git diff where the change is made. Is there a difference between these two techniques?

推荐答案

使用 ng-controller 指令的控制器:

Controller using a ng-controller directive:

  • ng-controller 元素上创建了一个新的 $scope.
  • 显式视图到控制器的连接
  • 通过检查元素等可见
  • A new $scope is created on ng-controller element.
  • Explicit view-to-controller connection
  • Visible with inspect element, etc

路由中的控制器:

  • ng-view 元素上为每个路由创建一个新的 $scope.
  • 控制器可以请求路由解析中定义的依赖项.
  • 可选的视图到控制器连接.建议采用命名约定,将控制器的路由映射到视图.
  • A new $scope is created per route on the ng-view element.
  • The controller can request dependencies defined in the route resolve.
  • Optional view-to-controller connection. Recommended to have a naming convention that maps routes to controllers to views.

这篇关于ng-controller 指令和路由中的控制器有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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