搭完框架后,该去实现里面的功能了。
实现删除功能:
AngularJS默认提供了一个ngClick事件, 当我去点click的时候,它会触发一个表达式。(带有"ng-"的,都会触发脏检查。)
首先在JS页面绑一个表达式,叫remove事件。$scope.remove(), 所以ng-click=“remove()
$scope.remove(): 根据Id去删除对应的那条信息。---->$scope.remove(id)
关于remove方法体里面用到的知识点:
angular里面的有一个迭代器,forEach:
Invokes the iterator
function once for each item in obj
collection, which can be either an object or an array. The iterator
function is invoked with iterator(value, key, obj)
, where value
is the value of an object property or an array element, key
is the object property key or array element index and obj is theobj
itself. Specifying a context
for the function is optional.
It is worth noting that .forEach
does not iterate over inherited properties because it filters using the hasOwnProperty
method.
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
Usage
angular.forEach(obj, iterator, [context]);
Arguments
Param | Type | Details |
---|---|---|
obj | ObjectArray | Object to iterate over. |
iterator | Function | Iterator function. |
context
(optional)
| Object | Object to become context ( |
具体到这个例子的应用为:
$scope.remove = function(id){ var index = -1; angular.forEach($scope.cart,function(item,key){ if(item.id===id){ index = key; } }) //通过对数组的操作去删除:从第index位开始,删除1位。 if(index !== -1){ $scope.cart.splice(index,1) }
最后在button上加ngClick:
<button type="button" ng-click="remove(item.id)" class="btn btn-danger">移除</button>
注意:
实现清空购物车功能
- ng-click="remove(item.id)" 不用写成$scope.remove();
- 通过ngClick方法后都会有一个脏检查:脏检查会检查整个cart。当检测到cart里面有数据改变时,总购买数和总购买价也会跟着改变。
只需要在button上加ngClick,就实现了清空功能了。
<button type="button" ng-click="cart={}" class="btn btn-danger">清空购物车</button>
使用ngShow事件优化
The ngShow
directive shows or hides the given HTML element based on the expression provided to thengShow
attribute. The element is shown or hidden by removing or adding the .ng-hide
CSS class onto the element. The .ng-hide
CSS class is predefined in AngularJS and sets the display style to none (using an !important flag). For CSP mode please add angular-csp.css
to your html file (see ngCsp).
<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="myValue"></div>
<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="myValue" class="ng-hide"></div>
When the ngShow
expression evaluates to a falsy value then the .ng-hide
CSS class is added to the class attribute on the element causing it to become hidden. When truthy, the .ng-hide
CSS class is removed from the element causing the element not to appear hidden.
此时,在table上面加上ngShow:
<table class="table" ng-show="cart.length">
在table外加上:
<p ng-show="!cart.length">您的购物车为空</p>
此时的页面显示为: