返回介绍

else

发布于 2024-12-24 22:41:42 字数 3788 浏览 0 评论 0 收藏 0

18.14. 示例:模板控制语句 if/else

这个示例是尝试实现:

  <div ng-controller="TestCtrl">
    <if true="a == 1">
        <p>判断为真, { { name } }</p>
      <else>
        <p>判断为假, { { name } }</p>
      </else>
    </if>

    <div>
      <p>a: <input ng-model="a" /></p>
      <p>name: <input ng-model="name" /></p>
    </div>
  </div>

考虑实现的思路:

  • `else` 与 `if` 是两个指令,它们是父子关系。通过 scope 可以联系起来。至于 scope 是在 link 中处理还是 controller 中处理并不重要。
  • `true` 属性的条件判断通过 `$parse` 服务很容易实现。
  • 如果最终效果要去掉 `if` 节点,我们可以使用注释节点来“占位”。

JS 代码:

 1   var app = angular.module('Demo', [], angular.noop);
 2   
 3   app.directive('if', function($parse, $compile){
 4     var compile = function($element, $attrs){
 5       var cond = $parse($attrs.true);
 6       
 7       var link = function($scope, $ielement, $iattrs, $controller){
 8         $scope.if_node = $compile($.trim($ielement.html()))($scope, angular.noop);
 9         $ielement.empty();
10         var mark = $('<!-- IF/ELSE -->');
11         $element.before(mark);
12         $element.remove();
13   
14         $scope.$watch(function(scope){
15           if(cond(scope)){
16             mark.after($scope.if_node);
17             $scope.else_node.detach();
18           } else {
19             if($scope.else_node !== undefined){
20               mark.after($scope.else_node);
21               $scope.if_node.detach();
22             }
23           }
24         });
25       }
26       return link;
27     }
28   
29     return {compile: compile,
30             scope: true,
31             restrict: 'E'}
32   });
33   
34   app.directive('else', function($compile){
35     var compile = function($element, $attrs){
36       
37       var link = function($scope, $ielement, $iattrs, $controller){
38         $scope.else_node = $compile($.trim($ielement.html()))($scope, angular.noop);
39         $element.remove();
40       }
41       return link;
42     }
43   
44     return {compile: compile,
45             restrict: 'E'}
46   });
47   
48   app.controller('TestCtrl', function($scope){
49     $scope.a = 1;
50   });
51   
52   angular.bootstrap(document, ['Demo']);

代码中注意一点,就是 if_node 在得到之时,就已经是做了变量绑定的了。错误的思路是,在 $watch 中再去不断地得到新的 if_node

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文