AngularJS双向数据绑定
ng-model与ng-bind指令
这两个指令是实现双向数据绑定的最主要的指令,区别如下:
ng-bind has one-way data binding ($scope –> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.
ng-model is intended to be put inside of form elements and has two-way data binding ($scope –> view and view –> $scope) e.g. .
总结来说就是ng-bind实现的是单向的数据绑定,我们可以在一个span标签中绑定一个数据项,让这个span标签中一直显示这个数据项的值。
而ng-model一般去实现双向的数据绑定,一般会用在表单输入中,比如input标签,我们不仅可以在input输入框中显示数据项的值,也可以通过input的输入来修改数据项的值。
实例:
<label class="col-md-2 control-label">邮箱:</label>
<div class="col-md-10">
<input type="email" class="form-control" placeholder="推荐使用126邮箱" ng-model="userInfo.email">
</div>
动态切换标签样式
html
<div ng-controller="CSSCtrl">
<p class="text-{{color}}">测试CSS样式</p>
<button class="btn btn-default" ng-click="setGreen()">绿色</button>
</div>
js
var myCSSModule = angular.module('MyCSSModule', []);
myCSSModule.controller('CSSCtrl', ['$scope',
function($scope) {
$scope.color = "red";
$scope.setGreen = function() {
$scope.color = "green";
}
}
])
这里controller在$scope中定义了变量color,以及函数setGreen,
而在html中我们使用{{color}}来动态地取出数据模型的值,
在使用了setGreen函数后,我们修改了后台的数据的color,html的class也会动态的更新
ng-show和ng-hide
html
<div ng-controller='DeathrayMenuController'>
<button ng-click='toggleMenu()'>Toggle Menu</button>
<ul ng-show='menuState.show'>
<li ng-click='stun()'>Stun</li>
<li ng-click='disintegrate()'>Disintegrate</li>
<li ng-click='erase()'>Erase from history</li>
</ul>
<div/>
js
var myCSSModule = angular.module('MyCSSModule', []);
myCSSModule.controller('DeathrayMenuController', ['$scope',
function($scope) {
$scope.menuState={show:false};
$scope.toggleMenu = function() {
$scope.menuState.show = !$scope.menuState.show;
};
}
])
在这个示例中,可以学习到ng-show命令,后面跟的变量是一个true或者false值的变量,根据这个true和false的值来确定是否需要显示这个标签。
toggle()的实现就是每次相反一下$scope.menuState即可以实现
ng-class
css
.error {
background-color: red;
}
.warning {
background-color: yellow;
}
html
<div ng-controller='HeaderController'>
<div ng-class='{error: isError, warning: isWarning}'>{{messageText}}</div>
<button ng-click='showError()'>Simulate Error</button>
<button ng-click='showWarning()'>Simulate Warning</button>
</div>
js
var myCSSModule = angular.module('MyCSSModule', []);
myCSSModule.controller('HeaderController', ['$scope',
function($scope) {
$scope.isError = false;
$scope.isWarning = false;
$scope.showError = function() {
$scope.messageText = 'This is an error!';
$scope.isError = true;
$scope.isWarning = false;
};
$scope.showWarning = function() {
$scope.messageText = 'Just a warning. Please carry on.';
$scope.isWarning = true;
$scope.isError = false;
};
}
])
这个示例中的关键就是ng-class命令:
ng-class='{error: isError, warning: isWarning}'
我们通过控制器的isError和isWarning两个变量就可以来给标签动态地加上一个classname