這回輪到使用NG演練KO範例8 - if及with的應用

Live Demo

<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
  <meta charset="utf-8">
  <title>Lab 8 - ng-if應用</title>
  <style>
    span { margin: 5px; }
  </style>  
</head>
<body ng-controller="defaultCtrl">
    <ul>
        <li ng-repeat="player in model.players">
            <span>{{player.name}}</span>
            <!-- 
                沒有bestRecord時隱藏<span>區塊,但是其中的內容還是會被解析,
                不過NG對繫結屬性設定有較高容錯力,不會拋出JavaScript錯誤
            -->
            <span ng-hide="!player.bestRecord">
                (最佳成績: 
                    <span ng-bind="player.bestRecord.score | number:0"></span>
                    <span ng-bind="player.bestRecord.date"></span>)
            </span>
        </li>
    
    </ul>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
  <script>
    angular.module("sampleApp", [])
    .controller("defaultCtrl", function($scope) {
      
      function player(name) {
          var self = this;
          self.name = name;
          self.bestRecord = null;
          self.setBestRecord = function (d, s) {
              self.bestRecord = {
                  date: d, score: s
              };
          };
      }      
      function myViewModel() {
        var self = this;
        self.players = [];
        //加入兩筆測試資料
        //第一筆資料有最佳成績(含日期及分數)
        var p1 = new player("Darkthread");
        p1.setBestRecord("2012-06-01", 65535);
        self.players.push(p1);
        //第二筆資料無最佳成績
        var p2 = new player("Jeffrey");
        self.players.push(p2);        
      }
      $scope.model = new myViewModel();
    });
  </script>
</body>
</html>

使用ng-hide/ng-show時,即使沒有資料不需顯示,DOM元素存在但為隱藏狀態。但與KO有點不同,當player.bestRecord == undefined或null時,data-bind="text: bestRecord.date"會引發錯誤,在NG僅為無資料不致出錯。

若希望條件不成立時不要在DOM出現,可使用ng-if: Live Demo

    <ul>
        <li ng-repeat="player in model.players">
            <span>{{player.name}}</span>
          <span ng-if="player.bestRecord">
                (最佳成績: 
                    <span ng-bind="player.bestRecord.score | number:0"></span>
                    <span ng-bind="player.bestRecord.date"></span>)
            </span>
        </li>
    </ul>

至於KO的with,NG並沒有對應的Directive。

[NG系列]
http://www.darkthread.net/kolab/labs/default.aspx?m=post&t=angularjs

Comments

Be the first to post a comment

Post a comment