AngularJS 除了使用雙大括號 {{}} 表達式來讓資料跟 Model 綁定之外 ,也可以使用 ng-bind 這個屬性來做到這個效果。 主要的差異在於當我們在 html 的 tag 裡都是使用雙大括號表達式的時候, AngularJS 未載入完成或是載入失敗的時候,我們可能就會看到畫面上出現 {{expression}} 這樣的內容,雖然當 AngularJS 載入完成後, {{expression}} 會馬上變成要顯示的資料,但是我們可以直接透過 ng-bind 這個屬性來直接避免掉這樣的問題, 而且一樣可以在這個屬性裡直接做一些簡單的邏輯計算。

使用的方法非常簡單,這次我們來做一個可以讓使用者輸入數量與單價,然後畫面上就會直接算出總價的小範例。

做完的效果就如下所示:

來看看怎麼做,首先準備好需要的 html 的內容,然後記得在 div 先加上 ng-app 屬性,程式碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="well" ng-app>
    <h1>ng-bind Demo</h1>
    <hr>
    <label>Quantity:</label>
    <!-- 第二步,在 input 標籤新增一個 ng-model 屬性,值給一個你想要的變數名稱 -->
    <input type="number" ng-model="quantity" placeholder="Enter a number here">
    <br/> <br/>
    <label>Price:</label>
    <input type="number" ng-model="price" placeholder="Enter a number here">
    <hr>
    <span>總價為:</span> <span> {{quantity * price}}</span> <span></span>

</div>

在 顯示計算後金額 的 span 部分,這次我們就不用原本的 AngularJS 表達式 {{quantity * price}} 來與 model 做資料繫結算出金額,而是使用 ng-bind 這個屬性,先幫這個 span 加上 ng-bind 的屬性,程式碼如下:

1
<span>總價為:</span> <span ng-bind=""></span> <span></span>

把原本在雙括號表達式裡的內容:quantity * price,寫在 ng-bind 的屬性裡,這樣就完成了,但是只做到這樣的話,在還沒輸入任何數字之前,畫面上會直接顯示出 NaN,這是因為沒有設定預設值的關係,那…使用 ng-bind 的時候能跟使用表達式時一樣加上預設值嗎?其實用法跟表達式一樣,所以記得要加上預設值,以免畫面上出現 NaN。

加上預設值後的程式碼如下:

1
<span>總價為:</span> <span ng-bind="quantity * price || '(未輸入金額與數量)'"></span> <span></span>

這樣範例就完成嘍,動手一起寫看看吧。

點此可以看完整程式碼範例

Comments