angular學習筆記 十四 watch 2

2021-09-06 15:35:42 字數 2714 閱讀 6704

下面來看乙個$watch的比較複雜的例子:

還是回到一開始講的購物車例子,

給它新增乙個計算總價和折扣的功能,如果總價超過500,則優惠10%:

**如下:

doctype html

>

<

html

>

<

head

>

<

title

>11.1$watch監控資料變化

title

>

<

meta

charset

="utf-8"

>

<

script

src="../angular.js"

>

script

>

<

script

src="script.js"

>

script

>

head

>

<

body

>

<

div

ng-controller

="cartcontroller"

>

<

h1>your shopping cart

h1>

<

table

>

<

tr ng-repeat

="item in items"

>

<

td>}

td>

<

td><

input

ng-model

="item.quantity"

/>

td>

<

td>}

td>

<

td class

="red"

>}

td>

<

td><

button

ng-click

="remove($index)"

>remove

button

>

td>

tr>

table

>

<

hr>

<

table

>

<

tr>

<

td>總價: <

span

class

="del"

>

}span

>

td>

tr>

<

tr>

<

td>折扣: <

span

class

="red"

>

}span

>

td>

tr>

<

tr>

<

td>現價: <

span

class

="green"

>

}span

>

td>

tr>

table

>

div>

body

>

html

>

function

cartcontroller ($scope) ,,,

];$scope.remove = function

(index);

$scope.bill =;

$scope.compute = function

() $scope.bill.all

=total;

$scope.bill.discount

= total >= 500 ? total*0.1 : 0;

$scope.bill.now

= $scope.bill.all -$scope.bill.discount

};$scope.$watch('items',$scope.compute,true

);}

把需要計算的三個資料: 總價,折扣,現價,放在乙個bill物件中,

監測商品列表items陣列的變化,設定$watch的第三個引數為true,這樣,商品的資料一旦發生變化,就會呼叫compute方法,重新計算bill物件中的三個資料

這個例子的js還可以寫成這樣:

function

cartcontroller ($scope) ,,,

];$scope.remove = function

(index);

$scope.bill =;

$scope.compute = function

() $scope.bill.all =total;

$scope.bill.discount = total >= 500 ? total*0.1 : 0;

$scope.bill.now = $scope.bill.all -$scope.bill.discount

};$scope.$watch($scope.compute);

}

angular學習筆記 十四 watch 1

本篇主要介紹 watch的基本概念 watch是所有控制器的 scope中內建的方法 scope.watch watchobj,watchcallback,ifdeep watchobj 需要被檢測的物件,可以是以下任意一種 1.某個資料,監測這個資料的值是否發生變化 2.一條angular表示式,...

Angular學習筆記 Angular生命週期

生命週期函式通俗的講就是元件建立 元件更新 元件銷毀的時候會觸發的一系列的方法。當 angular 使用建構函式新建乙個元件或指令後,就會按下面的順序在特定時刻呼叫這些生命週期鉤子方法。當 angular 使用建構函式新建乙個元件或指令後,就會按下面的順序在特定時刻呼叫這些生命週期鉤子方法 鉤子用途...

Angular學習筆記

1.nodejs 2.npm 3.cnpm 4.yarn 4.vscode 1.建立專案的 命令 ng new project name style scss 引數 style 使用的css型別,可以是css,sacc,scss,less,預設值是css 2.初始化node modules 命令 1...