加载中...

业务处理


9.3. 业务处理

简单来说,当一个锚点路由定义被匹配时,会根据模板生成一个 $scope ,同时相应的一个 controller 就会被触发。最后模板的结果会被填充到 ng-view 中去。

从上面的例子中可以看到,最直接的方式,我们可以在模板中双向绑定数据,而数据的来源,在 controller 中控制。在 controller 中,又可以使用到像 $scope$routeParams 这些服务。

这里先提一下另外一种与锚点路由相关的服务, $route 。这个服务里锚点路由在定义时,及匹配过程中的信息。比如我们搞怪一下:

  1. angular.module('ngView', [],
  2. function($routeProvider){
  3. $routeProvider.when('/a',
  4. {
  5. template: '{{ title }}',
  6. controller: function($scope){
  7. $scope.title = 'a';
  8. }
  9. }
  10. );
  11. $routeProvider.when('/b',
  12. {
  13. template: '{{ title }}',
  14. controller: function($scope, $route){
  15. console.log($route);
  16. $route.routes['/a'].controller($scope);
  17. }
  18. }
  19. );
  20. }
  21. );

回到锚点定义的业务处理中来。我们可以以字符串形式写模板,也可以直接引用外部文件作为模板:

  1. angular.module('ngView', [],
  2. function($routeProvider){
  3. $routeProvider.when('/test',
  4. {
  5. templateUrl: 'tpl.html',
  6. controller: function($scope){
  7. $scope.title = 'a';
  8. }
  9. }
  10. );
  11. }
  12. );

tpl.html 中的内容是:

  1. {{ title }}

这样的话,模板可以预定义,也可以很复杂了。

现在暂时忘了模板吧,因为前面提到的,当前 ng-view 不能有多个的限制,模板的渲染机制局限性还是很大的。不过,反正会触发一个 controller ,那么在函数当中我们可以尽量地干自己喜欢的事:

  1. angular.module('ngView', [],
  2. function($routeProvider){
  3. $routeProvider.when('/test',
  4. {
  5. template: '{{}}',
  6. controller: function(){
  7. $('div').first().html('<b>OK</b>');
  8. }
  9. }
  10. );
  11. }
  12. );

那个空的 template 不能省,否则 controller 不会被触发。


还没有评论.