有角度的ngRoute'Controller'声明是否必要? [英] Is the angular ngRoute 'Controller' declaration necessary?

查看:93
本文介绍了有角度的ngRoute'Controller'声明是否必要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了api和开发人员指南之后,我仍然不理解通过在给定路径中声明'controller'而提供的功能.现在,在我的视图中,我只是将我的控制器声明为ng-controller指令. ngRoute是否只是提供替代方法?

After reading both the api and the developer guide, I still don't understand the functionality provided by declaring 'controller' in a given route. Right now I just have my controllers declared as ng-controller directives in my views. Is ngRoute simply providing an alternative method?

要在代码中明确说明我的问题,请参见以下内容:

To make my question explicit in code, see below:

--Index.html
...
<body ng-app="MyApp">
  <div ng-view>
  </div>
</body>

--View.html
<div id="myView" ng-controller="MyController">
...
</div>

--Route.js
var app = angular.module('MyApp', [ require('angular-route') ]);

app.controller('MyController', ['$scope', function ($scope) {
  console.log('this gets executed as I would expect');
}])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', { templateUrl: '/Index.html' })
    .when('/view', { templateUrl: '/View.html' });
    // below line makes no difference as an alternative to above
    //.when('/view', { templateUrl: '/View.html', controller: 'MyController' });
}]);

推荐答案

有两种方法为视图定义控制器.

There are two ways to define controller for a view.

  1. 在ng-route的控制器声明中要么
  2. 在ng-controller中查看.

任何一个都可以.

这篇关于有角度的ngRoute'Controller'声明是否必要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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