文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
else
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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论