I have tried to simulate a cart (only partially completed). I just wanted to see how the code upto this point can be enhanced. I am trying to learn about the usage of directive
s.
Here I have used 2 directives:
msgpallette
- to show the messages when something is added to the cartitem-container
- to show each item in menu
A demo of the same is provided at plunkr
Do tell me whether I have used directives properly. If not, do suggest code changes with explanations.
HTML
<body ng-controller="MainCtrl">
<div id="msger">
<msgpallete msg="message" ng-show='show'>{{message}}
</msgpallete>
</div>
<p ng-repeat = "item in items">
<item-container
startcounter = 1
resetter = 'reset'
name = {{item.name}} >
{{item.name}}
</item-container><br><br>
</p>
<p ng-repeat = "order in orders">
<order-container >
{{order.name}}
</order-container><br><br>
</p>
</body>
JS
angular.module('myApp',[])
.controller('MainCtrl', function($scope, $timeout) {
$scope.items = [
{'name':'kabab'},
{'name':'noodles'},
{'name':'chicken'},
{'name':'egg'}
]
$scope.resettrigger = function () {
$scope.reset = true;
$timeout(function() {
$scope.reset = false;
},100)
}
$scope.show=0;
$scope.addMsg = function (qty,item) {
$timeout.cancel($scope.promise);
$scope.show = true;
msg = "Added "+qty+" "+item+" to the cart";
$scope.message = msg;
$scope.promise = $timeout(function() {
$scope.show = false;
},3000)
}})
.directive('msgpallete',function(){
return{
restrict:"E",
transclude:true,
scope:{},
template:"<h4 ng-transclude ></h4>"
}
})
.directive('itemContainer',function(){
return {
controller: function() {return {}},
restrict:'E',
scope:{
resetter:"="
},
transclude:true,
link:function(scope,elem,attr){
scope.qty = attr.startcounter
scope.add = function(){
scope.qty++;
}
scope.remove = function(){
scope.qty--;
}
scope.reset = function(){
console.log("attr.item:"+attr.name);
scope.$parent.addOrder(attr.name)
scope.$parent.addMsg(scope.qty,attr.name)
console.log("value when submitted:" + scope.qty + "name:"+ attr.name);
scope.qty = attr.startcounter;
scope.$parent.resettrigger();
}
scope.$watch(function(attr){
return attr.resetter
},
function(newValue){
if(newValue === true){
scope.qty = attr.startcounter;
}
});
},
template:"<button ng-click='reset();'>Add to cart</button>  "+
"<button ng-click='remove();' >-</button> "+
"{{qty}} " +
"<button ng-click='add();'>+</button>  "+
"<a ng-transclude> </a>"
}
});