angularjs - Angular ngRoute 'Controller' 声明是否必要?

标签 angularjs ngroute

阅读完 api 和开发人员指南后,我仍然不明白在给定路由中声明“ Controller ”所​​提供的功能。现在我只是在我的 View 中将 Controller 声明为 ng-controller 指令。 ngRoute 只是提供一种替代方法吗?

为了在代码中明确我的问题,请参见下文:

--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' });
}]);

最佳答案

有两种方法可以为 View 定义 Controller 。

  1. 在 ng-route 的 Controller 声明中
  2. 在 View 的 ng-controller 中。

两者都可以。

关于angularjs - Angular ngRoute 'Controller' 声明是否必要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27314029/

相关文章:

javascript - 如何从js文件中获取html脚本src值?

javascript - AngularJS ngRoute 404页面未找到

angularjs - Angular JS 使用 $http() 获得响应,状态为 200,但数据为 null

angularjs - 如何使用一个输入控件应用多个 ng-pattern

angularjs - Angular Dart : ng-switch in ng-repeat

angularjs - Ng-重复 : Filter By Uniqueness

angularjs - Angular ngRoute : Why is $resolve not available on scope in directive link function?

javascript - ngClick with window.location.href 着陆重定向两次

angularjs - Typed.js jQuery 插件不适用于 ngRoute