私は以下のコードを持っています:
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
};
});
次に、「メイン」div のテンプレートを処理する他のコントローラーがあります。それらのコントローラーの1つで、それが呼び出さbasketService.addItem
れ、ビューが更新されますbasketCount()
(それがどのように起こるか完全には理解していません。何かがトリガーされていると思います)
が呼び出されたら、addItem
jQuery animate または fadeIn を実行したいと思います。ディレクティブを使用する必要があることはわかっていますが、addItem 関数を監視してから jQuery を実行するディレクティブを取得する方法がわかりません。ご覧のとおり、カスタム HTML 要素basketService
に設定されているプロパティを公開しようとしCartController Scope
ましたが、何かを追加しても HTML 要素が更新されず、ディレクティブ関数が呼び出されません。
ご協力いただきありがとうございます
これがプランカーです - http://plnkr.co/edit/gis0114bTRRJLHCdYnMG?p=preview