我有下面的代碼:有一個指令聽功能
HTML
<div id="header">
<h1>The JSON Store</h1>
<div class="cart-info" ng-controller="CartController" quantity="basketContents">
My Cart (<span class="cart-items">{{basketCount()}}</span> items)
</div>
</div>
<div id="main" ng-view></div>
的JavaScript
app.controller(
'CartController',
function ($scope, basketService) {
$scope.basketCount = basketService.getCount;
$scope.basketContents = basketService.items;
}
);
app.factory('basketService', function() {
return {
getCount: function() {
var basket = JSON.parse((localStorage.getItem('shoppingBasket') || '{ "items": [] }'));
var count = 0;
basket.items.forEach(function (element) {
count += element.quantity;
});
return count;
},
get items() {
var basket = JSON.parse((localStorage.getItem('shoppingBasket') || '{ "items": [] }'));
var quantities = basket.items.map(function (x) { return x.quantity; });
if (quantities.length > 0) {
var total = quantities.reduce(function (previousValue, currentValue) { return previousValue + currentValue; });
return total;
} else {
return 0;
}
},
addItem: function (item) {
var basket = JSON.parse((localStorage.getItem('shoppingBasket') || '{ "items": [] }'));
var itemStoredAlready = basket.items.filter(function (x) { return x.id === item.id; }).length === 1;
if (itemStoredAlready) {
var basketItem = basket.items.filter(function (x) { return x.id === item.id; })[0];
basketItem.quantity += parseInt(item.quantity, 10);
} else {
var basketItem = {};
basketItem.id = item.id;
basketItem.title = item.title;
basketItem.quantity = parseInt(item.quantity, 10);
basket.items.push(basketItem);
}
localStorage.setItem('shoppingBasket', JSON.stringify(basket));
}
};
});
app.directive('quantity', function() {
var linker = function (scope, element, attrs, basketService) {
scope.$watch(attrs.quantity, function (value, oldValue) {
if (value > oldValue) {
alert("added");
}
}, true);
};
return {
restrict: 'A',
link: linker
};
});
然後我有其他的控制器,處理te 「主」div的模板。在這些控制器的一個調用basketService.addItem
和觀點是basketCount()
更新(我不完全瞭解這種情況發生,事情是觸發,我認爲)
當addItem
叫我願做一些jQuery的動畫或淡入,我知道我必須使用一個指令,但我不明白我是如何得到指令來觀看addItem函數,然後做一些jQuery的東西。正如你所看到的,我試圖公開在中設置的basketService
和自定義HTML元素中的屬性,但是當添加了某些內容時,HTML元素沒有得到更新,並且指令函數沒有被調用。
感謝您的幫助
這裏有一個Plunker - http://plnkr.co/edit/gis0114bTRRJLHCdYnMG?p=preview
我已經在這裏工作,http://plnkr.co/edit/8Zgxj4zNIQh7LJ4AxxA4?p=preview通過使它成爲一個函數,並在視圖中調用,但這一切似乎都非常複雜的新手 – Jon