Moving element from position to position with jquery/angular - javascript

Well the problem is quite simple...
I have an array of movies div (image and desc) written with a simple ng-repeat...
Now when i choose one of them i want to do the following (A game of positions i suppose):
1)I want to take out that element from the array and with a smooth animation to enlarge it to some other place in the screen, without breaking the order of that array.
2)when i choose another film, i want that one that i selected before to get back to where it was, following my newly selected film to take the space of the one before it:
here is a simple practice page i created so someone can dig it more:
http://single.org.il/
(just press on one of the categories up there,a list of movies will appear down at the bottom of the page, the black screen in the middle is where i want my selected film to enter, it's allready happening but it breaks, a lot)
Thank you very much!

I recommend including the selection state as part of the data model, then binding the view based on the selection data. The important points being:
Track the selected item as part of the $scope, and selection state as part of the item data
Filter selected items out of the navigation list
Bind the detail view to the selected item
I created a simplistic jsfiddle to demonstrate the concept, http://jsfiddle.net/ZLvQD/1/. The key code points include the filtered navigation list:
<div ng-controller="ListController">
<ul>
<li ng-repeat="item in itemList | filter:{isSelected:false}"
ng-class="{selected: item.isSelected}" ng-click="select(item)">
{{item.desc}}</li>
</ul>
<div ng-hide="!selectedItem">
<hr/>
The selected item is:
<p class="selected">{{selectedItem.desc}}</p>
</div>
the data model including selection state:
$scope.itemList = [
{
"desc": "Item A",
"isSelected": false
},
...
and the controller tracking selection state:
$scope.selectedItem = null;
$scope.select = function(selectedItem) {
// Deselect existing
if ($scope.selectedItem) {
$scope.selectedItem.isSelected = false;
}
// Select new
selectedItem.isSelected = true;
$scope.selectedItem = selectedItem;
};
I'm afraid I do not know anything about the animation part.

Related

AngularJS ng-repeat render once and reuse

A view of my AngularJS app makes heavy use of ng-repeat directive. It is done like this:
<div ng-repeat="branches in company">
<p>{{branches.name}}</p>
<p>{{branches.location}}</p>
<div>
<select ng-model="branches.officeInformationType">
<option ng-repeat="offices in branches">{{offices.type}}</option>
</select>
<select ng-model="branches.officeInformationMeters">
<option ng-repeat="offices in branches">{{offices.meters}}</option>
</select>
<select ng-model="branches.officeInformationColor">
<option ng-repeat="offices in branches">{{offices.color}}</option>
</select>
</div>
</div>
The fact is, the second ng-repeat and and the others after it (offices in branches) are actually the same everytime, so it wouldn't need to be recalculated for every branch. It would need to be binded to the row it belonges to, for saving it later, so the branches.officeInformation model should still be watched by angular, but I would like to make the whole program more performant.
I am using angular-ui-router and when I change the view between my "Choose your office" view and any other, the lag is tremendous, almost at a minute of wait time when you leave the "Choose your office" page. It renders fast enough, 2 seconds for the whole rendering, but when I leave the page it takes a ton of time to change to the other view.
Any ideas, taking into consideration that the ng-model binding "branches.officeInformation.." is of importance?
EDIT: I have tried remove the nested ng-repeats and for each ng-repeat that I removed, the transition between states got faster and faster. When I removed all the nested ng-repeats the transition became instantaneous, hence why I believe it has to do with the ng-repeats.
The ng-repeats are tracked by $index and where possible I used :: for one time binding.
Thanks.
We can lazy load a dropdown's options right before the user interacts with it.
First, we initialize each dropdown with only the selected option, so you can see it when the dropdown is closed.
Then we attach an ng-focus directive to each dropdown. When our callback fires we can:
fully populate the options for that dropdown
remove all but the selected option from the previously active dropdown
I wasn't entirely sure of the structure of your data (it looks like some arrays have additional properties on them). So I chose to create "view model" objects that represent the UI. You can adapt this to your own structure.
Controller:
// Set up some test office options (null for no selection)
var allOffices = [null];
for (var i = 0; i < 50; i++) {
allOffices.push(i);
}
// activeDropdown holds the dropdown that is currently populated with the full list
// of options. All other dropdowns are only populated with the selected option so
// that it shows when the dropdown is closed.
var activeDropdown;
$scope.company = [
// Branch 1
[
// These objects represent each dropdown
{
// Just the selected option until the user interacts with it
options: ["0"],
selected: "0"
}, {
// Just the selected option until the user interacts with it
options: ["1"],
selected: "1"
}, {
// Just the selected option until the user interacts with it
options: [null],
selected: null
}
],
// Branch 2
[
// These objects represent each dropdown
{
// Just the selected option until the user interacts with it
options: ["2"],
selected: "2"
}, {
// Just the selected option until the user interacts with it
options: ["3"],
selected: "3"
}, {
// Just the selected option until the user interacts with it
options: [null],
selected: null
}
]
];
// When the user interacts with a dropdown:
// - fully populate the array of options for that dropdown
// - remove all but the selected option from the previously active dropdown's
// options so that it still shows when the dropdown is closed
$scope.loadOffices = function (dropdown) {
if (activeDropdown === dropdown) {
return;
}
dropdown.options = allOffices;
if (activeDropdown) {
activeDropdown.options = [activeDropdown.selected];
}
activeDropdown = dropdown;
};
Template:
<div ng-repeat="branch in company">
<div ng-repeat="dropdown in branch">
Selected: {{ dropdown.selected }}
<select ng-focus="loadOffices(dropdown)" ng-model="dropdown.selected">
<option ng-repeat="o in dropdown.options">{{ o }}</option>
</select>
</div>
</div>
Note that ng-focus was the only directive I needed to apply to each dropdown when I tested this. But you may need to add ng-keydown, ng-mouseover, ng-click, or others to get it to work in all scenarios including mobile.
I also noticed a potential styling issue. When you focus on a dropdown, we load all of the options for that dropdown. This may cause the width of the dropdown to change, so if you can set the same width for all of them you should be good.
If the number of options in each dropdown is huge, we may be able to optimize even further by writing some custom directives that interact and allow the actual DOM element options to be shared. But I suspect we won't have to go that far for this example.
Have you tried 'track by $index' ? it will reduce angular watches overhead.
something like that:
div ng-repeat="branches in company track by $index">
<p>{{branches.name}}</p>
<p>{{branches.location}}</p>
<div>
<select ng-model="branches.officeInformationType">
<option ng-repeat="offices in branches track by $index">{{offices.type}}</option>
</select>
<select ng-model="branches.officeInformationMeters">
<option ng-repeat="offices in branches track by $index">{{offices.meters}}</option>
</select>
<select ng-model="branches.officeInformationColor">
<option ng-repeat="offices in branches track by $index">{{offices.color}}</option>
</select>
</div>
</div>
First and foremost, thanks to those that helped me find the answer.
The problem was that I nested too many ng-repeats with too many event handlers attached to each repeated element. ng-models, ng-changes and ng-clicks were really heavy, but the number of elements was also out of control.
I solved this by using a single select without any nested ng-repeats, this select (and the options) are in a modal view, so a different controller. From that controller I return the select results, having only one select for all the elements in the page. When the data is returned from the modal, I use it from the main controller of the view.
Thanks again.

AngularJS: Custom directives not working with dirPagination

I am using AngularJS to create a page which contains a list of products that shows information such as a name, price, region etc. This is displayed kind of like an accordion with the name in the header and extra information in the body.
Since there could be a large amount of these items displayed I am using dirPagination (https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination) to paginate these items. My markup at the moment looks like this:
<div class="custom-list" dir-paginate="asset in assets | itemsPerPage: 10 track by $index">
<div class="custom-list-item" ng-class="{'tag-hover': isHoveredTag(asset)}">
<div class="custom-list-item-heading" ng-click="toggleShowAssetDetails(asset)">
<p class="col-lg-5">{{ asset.name }}</p>
<div class="col-lg-offset-2 col-lg-3 rating">
<rating value="asset.rating" />
</div>
<button ng-click="addAsset(asset)"><span class="glyphicon glyphicon-plus"></span></button>
<div class="clearfix"></div>
</div>
<div class="custom-list-item-content" style="display: none" animate="shouldShowAssetDetails(asset)">
...
</div>
</div>
</div>
As you can see I'm using paginate in a pretty standard way just looping through the items in an array and displaying 10 per page. I also have a directive called rating which looks at a value called rating in the item. This is a number from 1 - 5 which is used to display a star rating system next to the name. The directive looks like this:
var rating = function ($compile) {
return {
restrict: "E",
scope: {
value: "="
},
link: function (scope, element, attrs) {
scope.$watch(attrs.rating, function () {
for (var i = 1; i <= 5; i++) {
if (i <= scope.value) {
var starElement = angular.element("<span class=\"icon icon-crown\"></span>");
$compile(starElement)(scope);
element.append(starElement);
} else {
var emptyStarElement = angular.element("<span class=\"icon-empty icon-crown\"></span>");
$compile(emptyStarElement)(scope);
element.append(emptyStarElement);
}
}
})
}
}
}
This looks at the value and inserts the icons based on the value of rating (e.g if the rating was 2 the directive would insert two icon-crown icon spans and 3 icon-empty icon-crown icon spans.
This was working perfectly fine before I included the pagination. However now it will only work for the first 10 items. When you change the page, the rating will not change and just keep the same icons from the previous page, even if the values are different.
I understand this is because the directive sets everything at the beginning and it will not run when you change page because the items aren't reloading they are just being shown and hidden again. But the directive is manipulating the DOM so it doesn't update when the page changes.
The problem is I don't know how to resolve this. I thought about changing the directive to look for the pagination current page instead but then I don't have access to the current list item.
I'd appreciate any help on getting the directive to update the icons when the page is changed.
Update
Here's a link to a Plunker project showing the problem I'm having: http://plnkr.co/edit/VSQ20eWCwVpaCoS7SeQq?p=preview
This is a very stripped down version of the section on my app that I'm having an issue with. There's no styling included although I have kept the CSS class structure. I've also changed the icons to use bootstrap ones just to simplify the Plunker project.
The functionality is the same however. If you go from page 1 to page 2 notice how the stars remain the same despite that fact that the asset rating values are different. However if you go to page 3 and back to page 2 or 1 they will change. The reason this happens is because there are less items on page 3 and therefore when you go back to page 1 or 2 the remaining items will be called again to retrieve the rating values.
You simply need to remove or replace track by $index.
Tracking by $index will give you the following behavior:
There is an array of max 10 length that represents the items to show. The first item will have index 0.
You go to the next page and the items in the array are replaced.
The first item in the array will still have index 0. Since you are tracking by index and the index has not changed, AngularJS will not recreate the DOM node representing the item. Since the DOM node isn't recreated, the directive will not execute this time and the rating will not update.
If you go from page 3 to page 2, the directive will execute for the 7 last elements on page 2, since they didn't exist on page 3, so they are considered new this time.
If you really need to use track by you should use a property that is actually related to the object (and unique), for example:
dir-paginate="asset in assets | itemsPerPage: 10 track by asset.name"
Demo: http://plnkr.co/edit/A80tSEliUkG5idBmGe3B?p=preview

two ng-repeaters on the same page

I have a page with a list of items on it. Each row has a button. By pressing a button list item is added to another list on the same page (it's a typical "order" form). I'm using angular ng-repeater to show the first list. After user press a button an item info is added to JSON varaible. The question is what's the best way to show user's choice list on the same page? So far I'm think of adding an attribute to the first list so when user choose it, it'll be shown in the second list. But I also want first list to be modified by user without any changes to the second one. Any ideas?
Check the code below, the button ng-click directive is calling the function AddtoList2($index) to add the current List1 item to List2, optionally it removes the current item from List1.
At template side
<div ng-repeat="item1 in List1">
...
<input type="button" ng-click="AddtoList2($index)" />
</div>
<div ng-repeat="item2 in List2">
...
</div>
At controller side
$scope.List1 = [];
$scope.List2 = [];
$scope.AddtoList2 = function (idx) {
var item = $scope.List1[idx];
$scope.List2.push(item);
//If you want to remove from List 1
$scope.List1.splice(idx, 1)
};

Fuel UX Tree get unselected data

I Use Fuel UX tree plugin. And I need to get information about unselected item when mouse click.
At first, all items in tree are selected, and when I click on tree item, it's become unselected, but I cannot get information about this item, because this code:
$('#tree1').on('selected', function (evt, data) {
console.log(data);
}
returned only selected items. Are the way to get information about unselected items in tree?
I added an additional "unselected" event into my copy of the fuelUX code around line 100...
if($el.hasClass('tree-selected')) {
this.$element.trigger('unselected', {info: $el.data()});
$el.removeClass('tree-selected');
$el.find('i').removeClass(this.options['selected-icon']).addClass(this.options['unselected-icon']);
} else {
...
This sends me the data associated with the unselected item as well. Hope it helps you.

AngularUI: Correctly updating the models between two lists with a filter applied

I'm using Sortable within AngularUI to manage multiple sortable lists. I've got it working to the point where I can easily move items between the lists, and update their corresponding models accordingly. However, if I include a query filter I run into a bit of issues if the following takes place:
The user enters a search field for an item that is NOT the first entry of a list.
The user moves the first item in the filtered results from one list to another.
It seems to work, until the query is cleared and the initial lists are shown. While it seemed that you moved the entry when you had the query applied, you'll notice that after it's cleared the first entry in the unfiltered array was moved instead.
It seems that Sortable doesn't take filters into account when you are dragging and dropping. Here's the relevant HTML:
<p>Search: <input ng-model="query" /></p>
<div class="column-wrapper">
<ul ui-sortable="sortableTemplates" ng-model="list1" id="sortable1" class="connectedSortable">
<li ng-repeat="item in list1|filter:query" class="itemBox">{{item.name}}</li>
</ul>
<ul ui-sortable="sortableTemplates" ng-model="list2" id="sortable2" class="connectedSortable">
<li ng-repeat="item in list2|filter:query" class="itemBox">{{item.name}}</li>
</ul>
</div>
And the corresponding JS:
var app = angular.module('myApp', ['ui.sortable']);
app.controller('test', function($scope) {
$scope.list1 = [
{name: 'ABC'},
{name: 'DEF'},
{name: 'GHI'}
];
$scope.list2 = [
{name: 'JKL'},
{name: 'MNO'},
{name: 'QRS'}
];
$scope.sortableTemplates = {
connectWith: '.connectedSortable'
}
});
Here it is running on Plunker.
To replicate the problem, you can try doing a search for GHI, then moving GHI to list2. Then, clear the search box. ABC is the one that actually moves to list2 (as it is the first element in that array), and GHI remains in list one.
Is there a way to have sortable get along with Angular filters, so that the original index is preserved when sorting between lists?
(I'm new to using Angular as well as JQueryUI, so the answer may be glaringly obvious. I found similar questions, but nothing that seemed to directly address this issue.)
As you say ui-sortable is using the elements index to move it between the lists, so that when you move the first item in your filtered list it moves the first item in your original list.
One way around this is instead of filtering your lists is to hide the items you don't want to be able to move, rather than creating a new list as the filter in your ng-repeat does.
so in your html:
<li ng-repeat="item in list1" class="itemBox" ng-show="visible(item)">{{item.name}}</li>
ng-show will show or hide the element depending upon whether $scope.visible(item) returns true or false.
We therefore create a function in our controller which returns true if we want to see the element, i.e. it is not filtered out, and false if it is filtered out.
$scope.visible=function(item){
//create an array containing all of the elements in both lists
var lists=$scope.list1.concat($scope.list2);
// filter this list using our search term
var filteredItems=$filter('filter')(lists, $scope.query);
//if there are no matching items left in our list then return false
if (filteredItems.length===0){return false;}
//see if the current item is in the filtered list
if (($filter('filter')(filteredItems,item)).length===1){
return true;
} else {
return false;
}
}
I have created a plunker at http://plnkr.co/edit/JCQdcP?p=preview

Categories