AngularJS 數(shù)據(jù)->模板->數(shù)據(jù)->模板

2018-07-26 16:41 更新

現(xiàn)在要考慮的是一種在現(xiàn)實(shí)中很普遍的一個(gè)需求。比如就是我們可以輸入數(shù)值,來(lái)控制一個(gè)矩形的長(zhǎng)度。在這里,數(shù)據(jù)與表現(xiàn)的關(guān)系是:

  • 長(zhǎng)度數(shù)值保存在變量中
  • 變量顯示于某個(gè) input 中
  • 變量的值即是矩形的長(zhǎng)度
  • input 中的值變化時(shí),變量也要變化
  • input 中的值變化時(shí),矩形的長(zhǎng)度也要變化

當(dāng)然,要實(shí)現(xiàn)目的在這里可能就不止一種方案了。按照以前的做法,很自然地會(huì)想法,綁定 input 的 change 事件,然后去做一些事就好了。但是,我們前面提到過 ng-model 這個(gè)東西,利用它就可以在不手工處理 change 的條件下完成數(shù)據(jù)的展現(xiàn)需求,在此基礎(chǔ)之上,我們還需要做的一點(diǎn),就是把變化后的數(shù)據(jù)應(yīng)用到矩形的長(zhǎng)度之上。

最開始,我們面對(duì)的應(yīng)該是這樣一個(gè)東西:

<div ng-controller="TestCtrl">
  <div style="width: 100px; height: 10px; background-color: red"></div>
  <input type="text" name="width" ng-model="width" />
</div>


<script type="text/javascript">
angular.module('app', [], angular.noop)
.controller('TestCtrl', function($scope){
    $scope.width = 100;
});
angular.bootstrap(document.documentElement, ['app']);
</script>

我們從響應(yīng)數(shù)據(jù)變化,但又不使用 change 事件的角度來(lái)看,可以這樣處理寬度變化:

angular.module('app', [], angular.noop)
.controller('TestCtrl', function($scope){
  $scope.width = 100;
  $scope.$watch('width',
    function(to, from){
      $element.children(':first').width(to);
    }
  );
});

使用 $watch() 來(lái)綁定數(shù)據(jù)變化。

當(dāng)然,這種樣式的問題,有更直接有效的手段, ng 的數(shù)據(jù)綁定總是讓人驚異:

<div ng-controller="TestCtrl">
  <div style="width: 10px; height: 10px; background-color: red" ng-style="style">
  </div>
  <input type="text" name="width" ng-model="style.width" />
</div>


<script type="text/javascript">
angular.module('app', [], angular.noop)
.controller('TestCtrl', function($scope){
    $scope.style = {width: 100 + 'px'};
});
angular.bootstrap(document.documentElement, ['app']);
</script>
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)