Directive take other directive's data after deletion - javascript

Edit: Thanks to Simon Schüpbach, I was able to resolve the issue by changing the template. See the end for the solution.
Let's preface this by saying that we are beginner to soft-intermediate in Angular.
On one of our project, we are using angularjs 1.4.x and also ng-cart (https://github.com/snapjay/ngCart). It worked great but then we were confronted with a demand from our client that created new weird issues.
We added fsCounter, as a directive, to the cart page so user can add or remove items. This all work great but the users also have the option to delete an item from the cart view. Deletion works as expected BUT it seems to affect the scope to the item that takes it place.
Let me make it clearer :
Let's say we have 2 products in our cart page, it displays something like that
Product_1 {price} {counter} {total} delete_btn
Product_2 {price} {counter} {total} delete_btn
Each fsCounter is its own scope
return {
restrict: "A",
scope: {
value: "=value",
index: "=index"
},
link: //other logic
However when we delete the first item, visually and in the directives, the data seems to shift. So our second row will now inherit the first row's counter.
Directive's data looks like this:
Product_1:
itemId:3,
quantity:2,
{other data}
Product_2:
itemId:8,
quantity:5,
{other data}
But once we delete the first directive (We get the scope, remove the DOM element, destroy the scope) the second directive will now have this data:
Product_2:
itemId:3,
quantity:2,
{other data}
Here is the template code :
<div class="unItem" ng-repeat="item in ngCart.getCart().items track by $index">
<div class="photo"><img src="{[{ item.getImage() }]}" alt=""></div>
<div class="details">
<h3>{[{ item.getName() }]} <span>{[{ item.getPrice() | currency:$}]}</span></h3>
<md-select ng-model="attributes" placeholder="Attribut" class="select-attribut" ng-show="item.hasAttributes()" ng-change="item.updateSelected(attributes)">
<md-option ng-repeat="attr in item.getAttributes()" ng-selected="attr == item.getSelected()" ng-value="attr">{[{ attr }]}</md-option>
</md-select>
</div>
<div class="quantity">
<div fs-counter-dynamic value="itemQuantity"
data-min="1"
data-max="999"
data-step="1"
data-addclass="add-quantity"
data-width="130px"
data-itemid="{[{ item.getId() }]}"
data-editable
ng-model="itemQuantity"
name="quantity" id="quantity-{[{ item.getId() }]}",
index="{[{ item.getId() }]}"
></div>
</div>
<div class="total">Total : {[{ item.getTotal() | currency }]}</div>
<div class="delete"><a ng-click="ngCart.removeItemById(item.getId());"></a></div>
</div>
Is this normal behavior? Is there any way to force the directive to keeps its own data? From what I've understood, each directive has its own scope, so what I think happens is that, when we remove the first one, it keeps the data stored in some kind of array that says "directive 1 data is : " and when we delete the first directive, the second one becomes the first.
So basically, are we doing anything wrong or is there anyway to remap the data?
Hope it was clear enough,
Thanks!
Edit: added html code
Edit2: Answer :
New FsCounter template looks like this:
<div fs-counter-dynamic value="item._quantity"
data-min="1"
data-max="999"
data-step="1"
data-addclass="add-quantity"
data-width="130px"
data-itemid="{[{ item.getId() }]}"
data-editable
ng-model="item._quantity"
name="quantity" id="quantity{[{ item.getId() }]}"
></div>

Do you know ng-repeat, then you don't have such problems
<div ng-repeat="product in products">
<fs-counter index="product.index" value="product.value"></fs-counter>
</div>
and in your controller
$scope.products = [
{index:1, value:"Cola"},
{index:2,,value:"Fanta"}
]
to remove an element you just have to do
$scope.products.splice(0,1);
Edit:
I suggest to save all necessary data inside the item you use inside ng-repeat. Your problem is, that you mix data from array with other data from your $scope. It is possible to $watch changes in your directive, but if you set them with ng-repeat everything is done automatically.
$scope.products = [
{index:1, name:"Cola", price:1.50, image:"your/path.png", attributes:{...}},
{index:2, name:"Fanta", price:1.40, image:"your/path.png"}
]
And then in your html
<div class="unItem" ng-repeat="item in ngCart.products track by $index">
<div class="photo"><img ng-src="item.image" alt=""></div>
<div class="details">
<h3>{{item.name}} <span>{{item.price | currency}}</span></h3>
</div>
<div class="quantity">
<div fs-counter-dynamic value="item.quantity"
data-min="1"
data-max="999"
data-step="1"
data-addclass="add-quantity"
data-width="130px"
data-itemid="item.index"
data-editable
ng-model="item.quantity"
name="quantity" id="{{'quantity-' + $index}}",
index="item.index"
></div>
</div>
<div class="total">Total : {{ item.price * item.quantity | currency }}</div>
<div class="delete"><a ng-click="ngCart.removeItemById(item.index);"></a></div>
</div>

Related

How to call multiple angularjs service calls from within nested ng-repeat

I am making a simple sports goods shopping app in AngularJs.
I am in a situation where I have three nested ng-repeats.
First loop: Get the brand name. I have written angularjs service that calls the rest endpoint to fetch the lists of brands (Adidas, Yonex, Stiga, etc). I am calling this service as soon as the page(controller) gets loaded.
Second loop: For each brand, I want to display the category of products they are offering. Inside this loop, I want to execute a function/service that will take the brand name as input and get all the categories for the brand. For this, I also have an angularjs service that calls the rest endpoint to fetch the list of categories for a given brand name.
Third loop: For each brand and category, I want to display the products in that category. Inside this loop, I want to execute a function that will take the brand name and category as input and get all the products in that category. I an angularjs service call which will call the rest endpoint to fetch the products given the brand name and category.
Sample data set:
Adidas
-----T-Shirts
----------V-Neck
----------RoundNeck
-----Shoes
----------Sports Shoes
----------LifeStyle Shoes
Yonex
-----Badminton Racquet
----------Cabonex
----------Nanospeed
-----Shuttlecocks
----------Plastic
----------Feather
Stiga
-----Paddle
----------Procarbon
----------Semi-carbon
-----Ping Pong Balls
----------Light Weight
----------Heavy Weight
Please note that because of some constraints I cannot have a domain object on the REST side to mimic the data structure shown above.
I want to display the above data in a tree-like fashion (something on the same lines as shown above possibly with expand/collapse options).
Below are the code snippets.
CONTROLLER:
(function () {
'use strict';
angular.module('SportsShoppingApp.controllers').controller('sportsController', ['sportsService', '$scope', function (sportsService, $scope) {
$scope.brands = [];
$scope.categories = [];
$scope.products = {};
$scope.getBrands = function () {
sportsService.getBrands()
.then(loadBrands, serviceError);
};
var loadBrands = function(response) {
$scope.brands= response.data;
};
$scope.getCategories = function(brand) {
sportsService.getCategories(brand)
.then(loadCategories, serviceError);
};
var loadCategories = function (response) {
$scope.categories = response.data;
};
$scope.getProducts = function(brand, category) {
sportsService.getProducts(brand, category)
.then(loadProducts, serviceError);
};
var loadProducts = function (response) {
$scope.products = response.data;
};
var serviceError = function (errorMsg) {
console.log(errorMsg);
};
$scope.getBrands();
}]);
}());
HTML:
<div class="well">
<div class="row">
<div id="sportsHeader" class="col-md-3">
<div ng-repeat="brand in brands.data">
<div class="row">
<div class="col-md-9">{{brand}}</div>
</div>
<div ng-repeat="category in categories.data" ng-init="getCategories(brand)">
<div class="row">
<div class="col-md-9">{{category}}</div>
</div>
<div ng-repeat="product in products.data" ng-init="getProducts(brand, category)">
<div class="row">
<div class="col-md-9">{{product}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When I use the above HTML, only the brand names are displayed on the UI. The categories and their corresponding products are not displayed. I know that there is some overlapping that is happening. I am not sure if I am doing it the right way. I might be completely wrong with my approach. I am new to AngularJS. I want to know how to loop in nested ng-repeat so that each ng-repeat could call an angularjs service and also I want to display the data in the tree fashion as shown above. Can someone help me here?
I think that the ng-inits have to be placed on separate tags to the ng-repeats:
<div class="well">
<div class="row">
<div id="sportsHeader" class="col-md-3">
<div ng-repeat="brand in brands.data">
<div class="row">
<div class="col-md-9">{{brand}}</div>
</div>
<div ng-init="getCategories(brand)">
<div ng-repeat="category in categories.data">
<div class="row">
<div class="col-md-9">{{category}}</div>
</div>
<div ng-init="getProducts(brand, category)">
<div ng-repeat="product in products.data">
<div class="row">
<div class="col-md-9">{{product}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
You might have to juggle your bootstrap classes around also, moving ng-init is only to fix the angular part.
Move the ng-init directives outside of the ng-repeat to which they provide data.
<div class="well">
<div class="row">
<div id="sportsHeader" class="col-md-3">
<!-- MOVE init of categories here -->
<div ng-repeat="brand in brands.data" ng-init="getCategories(brand)">
<div class="row">
<div class="col-md-9">{{brand}}</div>
</div>
<!-- MOVE init of products here -->
<div ng-repeat="category in categories.data" ng-init="getProducts(brand, category)">
<div class="row">
<div class="col-md-9">{{category}}</div>
</div>
<div ng-repeat="product in products.data">
<div class="row">
<div class="col-md-9">{{product}}</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
The ng-init directive has a priority of 450; the ng-repeat, priority 1000. This means that when they are on the same element ng-init executes after the ng-repeat directive. The ng-repeat for categories.data won't execute its ng-init until it has a category. Thus its ng-init can't be used to populate the categories array.
Quick question. Is my approach correct ?
The approach works but it violates the Zen of Angular and the principles of an MV* Model View Whatever framework.
The model is the Single Source of Truth
Because the view is just a projection of the model, the controller is completely separated from the view and unaware of it. This makes testing a snap because it is easy to test your controller in isolation without the view and the related DOM/browser dependency.
--AngularJS Developer Guide -- Data-Binding
Having the ng-repeat and ng-init directives build the model creates a dependency that makes testing and debugging difficult. (As witnessed by this question.)
My advice is to learn how to build the model by chaining promises and using $q.all.

Angular JS view hasn't been updated properly

I have found an issue in AngularJS which relates to wrong update of view. It occurs from time to time. The problem is when model gets a new value, view is not updated by new model value, but old value is appended by new model value.
While troubleshooting I checked that model contains a correct value.
Here is a view.
<div class="container">
<div ng-repeat="p in point" id="{{'point-' + p.Id}}" class="{{p.BackgroundClass}}">
<div class="point-number">{{p.Id}}</div>
<div class="{{p.ImageClass}}"></div>
<div class="point-amount">{{p.Amount}}</div>
<div class="point-quantity">{{p.Quantity}}</div>
</div>
</div>
Controller code which contains SignalR events processing:
wetApiHubProxy.on('updatePointState', function (pointId, backgroundClassProp, imageClassProp) {
pointsService.getPointById(pointId).then(function (point) {
point.BackgroundClass = backgroundClassProp;
console.log('imageClassProp ' + point.ImageClass);
point.ImageClass = imageClassProp;
});
});
p.ImageClass is changing quite often. Changes/updates of view work in a correct way until sometimes occurs concatenation of old and new value.
Old p.ImageClass value is "point-state-configure".
New p.ImageClass value is "pump-state-off".
As a wrong result I have, where ImageClass contains concatenated values:
<div ng-repeat="p in points" id="point-4" class="point point-off" role="button" tabindex="0" style="">
<div class="point-number ng-binding">4</div>
<div class="point-state-configure pump-state-off" style=""></div>
<div class="point-amount ng-binding">926.93</div>
<div class="point-quantity ng-binding">417.35 L</div>
</div>
I have tried to call $scope.$apply() and $evalAsync, but that was hopeless. The strangest thing that issue occurs spontaneously. The only constant condition it's when $rootscope contains bigger amount of child scopes. Can anyone tell what place to dig and how to get rid of this problem?
class attribute is not intended to be used this way. You should use the ng-class directive instead.
I've created an example for you: https://jsfiddle.net/coldcue/o7q6gfs4/
JavaScript
angular.module('testApp', [])
.controller("TestController", function($scope) {
// Initialize the value
$scope.state = "state-blue";
// Change class on click
$scope.click = function() {
$scope.state = ($scope.state === "state-blue") ? "state-red" : "state-blue";
}
});
HTML
<div ng-controller="TestController">
<div ng-class="state">
Some label
</div>
<input type="button" ng-click="click()" value="Click me">
</div>
But there are many more ways to use ng-class, read more here: https://docs.angularjs.org/api/ng/directive/ngClass

Using same controller in two places in AngularJS

I am working on an Ionic app, screen has lists with checkboxes and option to select all. I am new to AngularJS and Ionic.
"Select All" works fine when using controller in parent element where Select all and other lists reside.
I want to move the Select All to sub-header so that "Select All" will be always visible when we scroll through.
I tried to use the same controller in both places but Select All didn't work, I just read the scope gets changed and the value won't get passed.
Is there any way to pass the changes or any other way to fix this?
And data will be populated from the services.
HTML
<ion-header-bar class="bar-light bar-subheader">
<div ng-controller="MainCtrl">
<ion-checkbox ng-model="selectAll" ng-click="checkAll()" >
<p>Select All</p>
</ion-checkbox>
</div>
</ion-header-bar>
<ion-content class="has-header">
<div class="list" ng-controller="MainCtrl">
<ion-checkbox ng-repeat="item in devList" ng-model="item.checked">
<div class="row">
<div class="col">
<p>{{ item.text }} - 99</p>
<p>{{ item.text }} - 99</p>
</div>
<div class="col right">
<p>{{ item.text }} - 99</p>
<p>{{ item.text }} - 99</p>
</div>
</div>
</ion-checkbox>
</div>
</ion-content>
JS
.controller('MainCtrl', function($scope) {
$scope.devList = [
{ text: "HTML5", checked: true },
{ text: "CSS3", checked: false },
{ text: "JavaScript", checked: false }
];
$scope.checkAll = function() {
if ($scope.selectAll) {
$scope.selectAll = true;
} else {
$scope.selectAll = false;
}
angular.forEach($scope.devList, function (item) {
item.checked = $scope.selectAll;
});
};
});
CodePen link
Each controller will have it's own $scope. So, two different instances of controllers might have the same code, but they will still have different scopes.
So, you want to pass the changes from one controller to another.
In that case, there are a few solutions:
Using events:
$scope has a few methods which can help you to handle these cases.
These methods:
$on(name, listener) - Listens on events of a given type/name.
$emit(name, args) - Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.
$broadcast(name, args) - Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.
These methods will allow you to rise events from one controller and handle them inside the others.
Shared services
Also, you can create the service which will be injected into different controllers and, lets say, first controller will read this shared data and the second will write the data to this shared service.
Here is an article with some examples - link.
You can chose the approach that you like more, but I prefer shared services. This approach keeps my controllers more clear and I can manage cross-controllers dependencies by injection this shared services.
Hope it will help you.
You cannot use 2 'ng-controllers' with same controllers because the scopes created from those 2 controllers will be different, as controller scopes are created using the constructor pattern.
Ideally you should use $stateProvider to define your routes and their corresonding template and controller like below:
But for simplicity sake I have forked your codepen and used a single controller at the parent level of the view and it is working fine: http://codepen.io/anon/pen/vGQJNj
<body ng-controller="MainCtrl">
<ion-header-bar class="bar-positive">
<h1 class="title">Checkboxes</h1>
</ion-header-bar>
<ion-header-bar class="bar-light bar-subheader">
<div>
<ion-checkbox ng-model="selectAll" ng-click="checkAll()" >
<p>Select All</p>
</ion-checkbox>
</div>
</ion-header-bar>
<ion-content class="has-header">
<div class="list">
<ion-checkbox ng-repeat="item in devList"
ng-model="item.checked"
ng-checked="item.checked">
<div class="row">
<div class="col">
<p>{{ item.text }} - 99</p>
<p>{{ item.text }} - 99</p>
</div>
<div class="col right">
<p>{{ item.text }} - 99</p>
<p>{{ item.text }} - 99</p>
</div>
</div>
</ion-checkbox>
<div class="item">
<pre ng-bind="devList | json"></pre>
</div>
<div class="item item-divider">
Notifications
</div>
<ion-checkbox ng-model="pushNotification.checked"
ng-change="pushNotificationChange()">
Push Notifications
</ion-checkbox>
<div class="item">
<pre ng-bind="pushNotification | json"></pre>
</div>
<ion-checkbox ng-model="emailNotification"
ng-true-value="'Subscribed'"
ng-false-value="'Unubscribed'">
Newsletter
</ion-checkbox>
<div class="item">
<pre ng-bind="emailNotification | json"></pre>
</div>
</div>
</ion-content>
</body>

AngularJS dirPaginate Only Filtering current page

I have included dir paginate into my angularjs project to handle pagination easily, it works well up until the point where I want to filter all the pages results.
The controller that contains the data and filter looks like so:
app.controller('listCtrl', function ($scope, services) {
$scope.sort = function(keyname){
$scope.sortKey = keyname; //set the sortKey to the param passed
$scope.reverse = !$scope.reverse; //if true make it false and vice versa
}
$scope.currentPage = 1;
$scope.pageSize = 10;
services.getPosts().then(function(data){
$scope.posts = data.data;
});
});
The dir-paginate looks like so
<div dir-paginate="data in posts | itemsPerPage:5 | orderBy:sortKey:reverse" class="col-xs-12 post">
<div id="title" class="col-xs-3"></div>
<div id="title" class="col-xs-9"></div>
<div id="poster" class="col-xs-3">
<img src="pics/house.jpg" id="avatar">
<a ng-if="data.user_name == '<?php echo $currentUser?>'" href="edit-post/{{data.post_id}}"> Edit </a>
</div>
<div class="col-xs-9">
<div class="col-xs-12">
<p class="timestamp">{{ data.post_datetime }}</p>
</div>
<div id="rant">
<span style="word-wrap: break-word;">{{ data.post_content }}</span>
</div>
<div id="stats" class="col-xs-12"> <img src="pics/comment.png"><span>3</span>
</div>
</div>
</div>
<dir-pagination-controls
max-size="5"
direction-links="true"
boundary-links="true" >
</dir-pagination-controls>
I call the sort function like so:
<button id="changeLikes" ng-click="sort('post_id')">ID</button>
It only sorts the current page of Data, if i use the pagination and click page 2 it will then only filter page 2 and so on, any ideas here would be of great help getPosts() returns post data via php with no group or order by clauses in the sql that would affect the angular.
Have you tried flipping the order of the filters, i.e.
<div dir-paginate="data in posts | orderBy:sortKey:reverse | itemsPerPage:5" class="col-xs-12 post">
The dir-paginate docs state:
itemsPerPage: The expression must include this filter. It is required
by the pagination logic. The syntax is the same as any filter:
itemsPerPage: 10, or you can also bind it to a property of the $scope:
itemsPerPage: pageSize. Note: This filter should come after any other
filters in order to work as expected. A safe rule is to always put it
at the end of the expression.

ng-repeat: how do I properly reference $odd or $even by variable?

How can I reference $odd or $even by variable in ng-repeat?
I am trying to do this:
<ng-repeat="item in items" ng-if="$odd">these are odd{{item}}</div>
<ng-repeat="item in items" ng-if="$even">these are even {{item}}</div>
By doing this:
<div ng-repeat="side in sides">
<div ng-include='template'></div>
</div>
//template
<ng-repeat="item in items" ng-if="side">these are {{side}} {{item}}</div>
//in the controller
$scope.sides = ['$odd','$even']
{{side}} results in $odd and $even text on the document where expected, but all the {{item}} are coming through.
I've tried ng-if="side", ng-if=side, ng-if={{side}}, ng-if=" 'side' ".
I'm sure this is just my rookie ignorance at play and its staring me right in the face.
Edit:::
Sorry I wasn't clear. Assigning $odd and $even was simple enough if I wanted to write out the whole layout longhand, which I relented and did for now. What I would like to do, however, is use ng-include to template the reused portions of the layout as much as possible. A very simplified version of my layout looks something like this:
What I would like to do is turn something like this:
<div class="outer-column1">
<div class="innercolumnA">
<div class="thumbnail" ng-repeat"thumbnail in thumbnail" ng-if"$even"></div>
</div>
<div class="innercolumnB">
<div class="thumbnail" ng-repeat"thumbnail in thumbnail" ng-if"$odd"></div>
</div>
</div>
<div class="outer-column2">
<div class="innercolumnA">
<div class="thumbnail" ng-repeat"thumbnail in thumbnail" ng-if"$even"></div>
</div>
<div class="innercolumnB">
<div class="thumbnail" ng-repeat"thumbnail in thumbnail" ng-if"$odd"></div>
</div>
</div>
into something like this:
<div ng-include="outer-column" ng-repeat="outercolumn in outercolumns"></div>
//template outer-column
<div class="outer-column">
<div ng-include="inner-column" ng-init="innercolumns = [$odd,$even] " ng-repeat="innercolumn in innercolumns"></div>
</div>
//template inner-column
<div class="innercolumn" ng>
<div ng-include="'thumbnail'" ng-repeat"thumbnail in thumbnail" ng-if"innercolumn"></div>
</div>
//template thumbnail
<div class="thumbnail"></div>
The question is: how can I reference the $odd and $even variables for ng-if indirectly? for example, I tried an ng-init="sides = [$odd,$even]" and passed that in the ng-repeat for the innercolumn template and put ng-if="side" into the template, but no go.
I also thought about passing a function like ng-if="whichSide(side)" That would return $odd or $even, but it seems like the $odd and $even variables are not defined on the $scope object...
But that's the spirit of what I'm trying to understand regarding the $odd and $even variables and indirectly referencing them.... Hope that makes sense. The project is working just fine, it's just annoying to make changes to 10 lines of code whenever I make an update vs. 3 lines of templated layout. Thanks!
$odd and $even are available variables in an ng-repeat. It looks like you are instead trying to evaluate a string literal. Observe the following example and model your working copy from there...
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="o in items" ng-if="$odd" class="odd">index: {{ $index }} value: {{ o }}</div>
<div ng-repeat="o in items" ng-if="$even" class="even">index: {{ $index }} value: {{ o }}</div>
</div>
// -- for visual demo. ng-if will work the same
.odd { background-color: dodgerblue; }
.even { background-color: tomato; }
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.items = [1, 2, 3, 4, 5];
})
JSFiddle Link - working demo
Also, I'm not entirely sure what your overall goal is, but in my example, I am applying classes to style $even and $odd for demonstration. AngularJS offers ngClassOdd and ngClassEven as an alternative for accomplishing this as well. Lastly, if you are evaluating both $even and $odd - all items will of course show.
Check out the ngRepeat docs for available variables you will have to evaluate
$index - iterator offset of the repeated element (0..length-1)
$first - true if the repeated element is first in the iterator.
$middle - true if the repeated element is between the first and last in the iterator.
$last - true if the repeated element is last in the iterator.
$even - true if the iterator position $index is even (otherwise false).
$odd - true if the iterator position $index is odd (otherwise false).

Categories