Last active
September 17, 2016 14:52
-
-
Save twlca/0981d556b64f3ba4a741d5dee5ba4b85 to your computer and use it in GitHub Desktop.
Demo for basic AngularJS ng-init and ng-model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> | |
<title>AngularJS ng-nit and ng-model</title> | |
</head> | |
<body> | |
<div ng-app ng-init="male_count=1;female_count=2"> | |
<p> | |
<label for="male_count">男性</label> | |
<input type="number" min="0" max="99" ng-model="male_count" name="male_count" /> | |
</p> | |
<p> | |
<label for="female_count">女性</label> | |
<input type="number min="0" max="99" ng-model="female_count" name="female_count" /> | |
</p> | |
<div><span>合計:{{ male_count + female_count }}</span></div> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
基本 ng-init 與 ng-model 用法
ng-init
用在初始化ng-model
的值。例如本例中,在網頁載入,使用者未曾作任何輸入前,即初始化<input>
的值。ng-model
可視為<input>
中的name
屬性,它可以在稍後在{{ ... }}
中引用,直接取得<input>
中改變的值。這是兩者最基本的用法。
ng-bind 取代
{{ ... }}
ng-bind 是稍為正統的作法,在於
ng-bind
是 directive,它 "觀察" 變數是否改變,若改變則反應在變數值的傳輸上。而{{...}}
是 "不拘" 變數是否改變,每次都重新 "refresh",某種程度上會造成效能損耗。以上例而言,第 17 行可以寫成
這樣的思維可以用在 filter 上,以及很多相關的應用。也就是說,若有合適的 directive,則採用 directive,而儘量減少使用
{{ ... }}