Book-AngularJS- Up and Running - Chapter-4
Examples
by kibria
HTML
<body ng-app='notesApp' ng-controller="MainCtrl as ctrl">
<form ng-submit="ctrl.submit()" name="myForm">
<input type="text" class="username" name="uname" ng-model="ctrl.user.username" required ng-minlength="4">
<input type="submit" value="Submit" ng-disabled="myForm.$invalid">
<div>
<h2>What are your favorite sports?</h2>
<div ng-repeat="sport in ctrl.sports" style='border: solid 1px #dfdfdf;'>
<label ng-bind="sport.label"></label>
<div>With Binding:
<input type="checkbox" ng-model="sport.selected" ng-true-value="YES" ng-false-value="NO">
</div>
<div>Using ng-checked:
<input type="checkbox" ng-checked="sport.selected === 'YES'">
</div>
<div>Current state: {{sport.selected}}</div>
</div>
</div>
<div>
<div ng-init="otherGender = 'other'">
<input type="radio" name="gender" ng-model="user.gender" value="male">Male
<input type="radio" name="gender" ng-model="user.gender" value="female">Female
<input type="radio" name="gender" ng-model="user.gender" ng-value="otherGender">{{otherGender}}</div>
<div>Current Gender: {{user.gender}}</div>
</div>
<hr/>
<div>
<div>
<select ng-model="ctrl.selectedCountryId" ng-options="c.id as c.label for c in ctrl.countries"></select>Selected Country ID : {{ctrl.selectedCountryId}}</div>
<div>
<select ng-model="ctrl.selectedCountry" ng-options="c.label for c in ctrl.countries"></select>Selected Country : {{ctrl.selectedCountry}}</div>
</div>
</form>
</body>
CSS
.username.ng-valid {
background-color: green;
}
.username.ng-dirty.ng-invalid-required {
background-color: red;
}
.username.ng-dirty.ng-invalid-minlength {
background-color: lightpink;
}
JavaScript
angular.module('notesApp', [])
.controller('MainCtrl', [function () {
var self = this;
self.submit = function () {
console.log('User clicked submit with ', self.user);
};
self.sports = [{
label: 'Basketball',
selected: 'YES'
}, {
label: 'Cricket',
selected: 'NO'
}, {
label: 'Soccer',
selected: 'NO'
}, {
label: 'Swimming',
selected: 'YES'
}];
this.countries = [{
label: 'USA',
id: 1
}, {
label: 'India',
id: 2
}, {
label: 'Other',
id: 3
}];
this.selectedCountryId = 2;
this.selectedCountry = this.countries[1];
}]);