Angular ngRoute“控制器”声明是否必要?

2024-04-27

阅读了 api 和开发人员指南后,我仍然不明白在给定路由中声明“控制器”所​​提供的功能。现在我只是在我的视图中将控制器声明为 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' });
}]);

有两种方法可以为视图定义控制器。

  1. 在 ng-route 的控制器声明中
  2. 在视图的 ng-controller 中。

任何一个都可以。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular ngRoute“控制器”声明是否必要? 的相关文章

随机推荐