angularjs探秘<四> 双向数据绑定

时间:2023-03-10 06:08:00
angularjs探秘<四> 双向数据绑定

双向数据绑定是angularjs的一大特性,这个特性在实际开发中省了不少事儿。之前第二篇提过数据绑定,这一篇从实际开发的案例中具体看下双向数据绑定的便捷。

首先看一个场景:

angularjs探秘<四> 双向数据绑定

注册/登录 中经常遇到这样的场景,来看看angular的解决方案。

HTML:

    <fieldset ng-controller="defaultInfo">
<legend>用户登录</legend>
<div class="box_a">
<label for="uName">用户名:</label>
<input class="text_a" id="uName" type="text" ng-model="uName">
<button ng-click="default_uName()">默认值</button>
</div>
<div class="box_a">
<label for="uPassword">密 码:</label>
<input class="text_a" id="uPassword" type="password" ng-model="uPassword">
<button ng-click="default_uPassword()">默认值</button>
</div>
<div class="box_a">
<input id="uTrue" type="checkbox" ng-model="uTrue">
<label for="uTrue">记住我</label>
<button ng-click="default_uTrue()">默认值</button>
</div>
</fieldset>

JS:

// defaultInfo控制器
MyApp.controller('defaultInfo',['$scope',function($scope){
$scope.uName = "";
$scope.uPassword = "";
$scope.uTrue = false;
// --
$scope.default_uName = function(){
$scope.uName = "miragefirefox@163.com";
}
$scope.default_uPassword = function(){
$scope.uPassword = "miragefirefox";
}
$scope.default_uTrue = function(){
$scope.uTrue = true;
}
}]);

ng-model 绑定标签与控制器的变量相对应,ng-click 挂载控制器点击事件,在控制器对应函数中给 model 重新赋值即可。

controller的数据通过事件绑定到model上,同样,controller也能读取到model上的数据(这里就不做演示了)。

有了双向数据绑定省去了过去反复读取DOM的繁琐过程,大大提高开发效率。

======================================================================================================================================

再来看一个动态修改样式的案例:

angularjs探秘<四> 双向数据绑定

HTML:

<!--html-->
<div ng-controller="bgColor" class="box_b" ng-class="{ngRed:bgRed ,ngBlue:bgBlue }">
<button ng-click="changeBg('r')">红色</button>
<button ng-click="changeBg('b')">蓝色</button>
</div>
<!--css-->
.ngRed{ background:red; }
.ngBlue{ background:blue; }

JS:

// bgColor控制器
MyApp.controller('bgColor',['$scope',function($scope){
$scope.bgRed = false;
$scope.bgBlue = false;
$scope.changeBg = function(color){
switch(color){
case 'r':
$scope.bgRed = true;
$scope.bgBlue = false;
break;
case 'b':
$scope.bgRed = false;
$scope.bgBlue = true;
break;
}
}
}]);

通过 ng-class 动态改变div背景色,ng-class 支持表达式赋值class样式;

{ngRed:bgRed ,ngBlue:bgBlue } bgRed值为true时使用ngRed样式,bgBlue值为true时则使用ngBlue样式,以此类推ng-class可以写很多样式。

controller 这块儿非常简单了根据传参切换 true/false 值即可。

======================================================================================================================================

菜单的显示/隐藏案例:

angularjs探秘<四> 双向数据绑定

HTML:

    <div ng-controller="toggleM">
<h1 ng-click="upDown()">菜单标题</h1>
<ul ng-show="onOff">
<li>目录一</li>
<li>目录二</li>
<li>目录三</li>
<li>目录四</li>
<li>目录五</li>
</ul>
</div>

JS:

// toggleM控制器
MyApp.controller('toggleM',['$scope',function($scope){
$scope.onOff = false;
$scope.upDown = function(){
$scope.onOff = !$scope.onOff;
}
}])

ng-show ng-hide 是angular专门为元素的显示/隐藏定制的指令,非常便捷。ng-showtrue 时元素显示,false时元素隐藏;ng-hide则相反。在controller中改变ng-show的值即可实现元素的显示/隐藏。

以上三个实际开发中常见的场景用angular的双向数据绑定实现起来比传统方式高效便捷多了。