Quantcast
Channel: 黑暗執行緒
Viewing all articles
Browse latest Browse all 2311

NG筆記11-依條件決定是否加入DOM

$
0
0

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

Live Demo

<!DOCTYPEhtml>
<htmlng-app="sampleApp">
<head>
<metacharset="utf-8">
<title>Lab 8 - ng-if應用</title>
<style>
    span { margin: 5px; }
</style>
</head>
<bodyng-controller="defaultCtrl">
<ul>
<ling-repeat="player in model.players">
<span>{{player.name}}</span>
<!-- 
沒有bestRecord時隱藏<span>區塊,但是其中的內容還是會被解析,
不過NG對繫結屬性設定有較高容錯力,不會拋出JavaScript錯誤
            -->
<spanng-hide="!player.bestRecord">
                (最佳成績: 
<spanng-bind="player.bestRecord.score | number:0"></span>
<spanng-bind="player.bestRecord.date"></span>)
</span>
</li>
</ul>
<scriptsrc="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>
<ling-repeat="player in model.players">
<span>{{player.name}}</span>
<spanng-if="player.bestRecord">
                (最佳成績: 
<spanng-bind="player.bestRecord.score | number:0"></span>
<spanng-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

Viewing all articles
Browse latest Browse all 2311

Trending Articles