Angular ng-repeat rendering issue for small lidt - angularjs

I have the 2 of objects below:
$scope.MyObj_1={
Id:"1",
Title:"Title1",
Items:[
{
Id:"1",
Comment:"Simple comment 1",
}
]
};
$scope.MyObj_2={
Id:"2",
Title:"Title1",
Items:[
{
Id:"2",
Comment:"Simple comment 2",
},
{
Id:"3",
Comment:"Simple comment 3",
},
{
Id:"4",
Comment:"Simple comment 4",
}
]
};
And I have this html template (just to simplify):
<ul>
<li ng-repeat="note in MyObj.Items" >{{item.Comment}}</li>
</ul>
When I set MyObj with MyObj_1 value and then I set MyObj with MyObj_2 I am getting rendering problem related to the slowness of ng-repeat. In fact ng-repeat starts by adding items of MyObj_2 and then removes the item related to MyObj_1.
I tried ng-cloak and $timeout but the behavior still the same.
I am wondering why ng-repeat did not remove old element first and then push new elements.

Angular.copy makes clone of object from source to destination.It deletes all objects from destination object and then copy properties from source.
Angular.merge appends the source object to destination.If destination object already has elements, it will remain there and new properties from source object will add to destination object.

The behavior is expected if you set the $scope.MyObj_2 = $scope.MyObj_1;
Then they will point to the same reference in memory.
What you need to use is angular.copy() which creates a deep copy of source like this
$scope.MyObj_2 = angular.copy($scope.MyObj_1);
Also, in the repeat you have a typeo, should be
<ul>
<li ng-repeat="note in MyObj.Items" >{{note.Comment}}</li>
</ul>

Related

VueJS Array update bug

I have a JSFiddle below to explain my problem but basically I have an array called tiles which has a title. When the instance is created() I add a field to this array called active
I then output this array in an <li> element and loop through it outputting the title and active objects. My problem is as you can see in the fiddle when I run v-on:click="tile.active = true" nothing happens to the active state written in the <li> element
but if I run v-on:click="tile.title = 'test'" it seems to update the active object and the title object.
Its strange behaviour I can't seem to work out why. Does anyone have any ideas?
https://jsfiddle.net/jgb34dqo/
Thanks
It's to do with Vue not knowing about your properties, change your array to this:
tiles: [
{
title: 'tile one',
active: false
},
{
title: 'tile two',
active: false
},
{
title: 'tile three',
active: false
}
]
This allows Vue to know about the active property and in turn it knows to monitor that variable.
It's worth looking at this link about Vue Reactivity as it helps with understanding how and when data will change automagically.
If you must add the properties after
take a look at $set. It allows you to add props to an object that then get watched by vue. See this fiddle, notice the change:
this.tiles.forEach(function(tile) {
// Tell vue to add and monitor an `active` prop against the tile object
this.$set(tile, 'active', false);
}.bind(this))

Create list of items of a single item at once

Angular task 1.5.x:
I have object like this:
{
id: 1,
name: "a",
items: [
{"holiday": "false", "day": "monday"},
{"holiday": "true", "day": "tuesday"...}
]
}
I want a new object to be created in the above way with click of a single button. Note I dont want to add each item separately, all at once. Means, for a single object with name "a", I want to add all items for all days at once.
I can make it work but I want to know the correct way.
ultimately we should be able to create a javascript object in the above format(without id)(I think this format is correct) and send it to server so it will work. But how to add html/angular code so I will get an object that way.
Please let me know for more info.
When using ng-model you do not have to fully define your object in order to have it constructed. E.g.:
Controller
$scope.object= {
items: []
};
var n = 7;
for (var i = 0; i < n; i++)
$scope.object.items({});
HTML
<input type="text" ng-model="object.name"/>
<div ng-repeat="currObj in object.items">
<input type="text" ng-model="currObj.holiday" />
<input type="text" ng-model="currObj.day" />
</div>
The general structure must be defined beforehand, but you do not have to initialize all the properties. They will receive values when binding is triggered (view -> model).
You can do like this :
Create a button in your view and use ng-click directive to capture on click event.
Html:
<button ng-click="createCopy()"></button>
Use angular.copy to create a deep copy of the source object.
This is what angular.copy does as explained in the docs :
Creates a deep copy of source, which should be an object or an array.
If no destination is supplied, a copy of the object or array is
created. If a destination is provided, all of its elements (for
arrays) or properties (for objects) are deleted and then all
elements/properties from the source are copied to it. If source is not
an object or array (inc. null and undefined), source is returned. If
source is identical to destination an exception will be thrown.
Controller:
$scope.mainObject = { id: 1, name: "a", items: [{"holiday": "false", "day": "monday"}, {"holiday": "true", "day": "tuesday"...}] };
$scope.createCopy = function (){
$scope.copyObject = angular.copy($scope.mainObject);
}

extracting information from array using knockout

I currently have an array being passed into my function and i wanted to pull out the information from the array so i can display it on the page.
This is what the array looks like:
EducationalClasses:[object, object]
first object contains:
classId: "324342",
className: "English 101"
second object contains:
classId: "231243",
className: "Reading"
when i do educationalClasses[0] i get the results as in first object. I wanted to create some sort of loop so that in my view page when i have:
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className></div>
<!--/ko-->
i would get English 101 and Reading displayed
This is what i have for my viewModel:
viewModel = function(educationalClasses){
....
self.className= ko.observable(educationalClasses.className); // what i want
}
How can i do this properly and so that all the items in the array are displayed without me having to use educationalClasses[0].className...educationalClasses[1].className
Technically, you don't need any observables for what you're doing here. You just need your viewmodel to have a member named educationalClasses that is an array (or observableArray). You can just wrap your raw data in an object, label it, and it goes.
If you want to change the array and have the view show the updates, you'll want an observableArray. If you want changes to the individual data items to show, you'd want them to be observables as well.
rawData = [{
classId: "324342",
className: "English 101"
}, {
classId: "231243",
className: "Reading"
}];
viewModel = function(educationalClasses) {
return {
educationalClasses: educationalClasses
};
};
ko.applyBindings(viewModel(rawData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<!-- ko foreach: educationalClasses -->
<div data-bind="text: className"></div>
<!--/ko-->

Access selectedItems of an <iron-list> on change

Having trouble understanding how to access the selectedItems property of an iron-list. When bound to a property of the parent, I can output it's contents using a template, but an observer or computed binding does not fire when it changes and I can't seem to output it's contents.
If anyone could point out what I'm doing wrong, how I can read the selectedItems for logic, or how I can observe changes to an iron-list selectedItems property, I would greatly appreciate the know how. Thanks.
Below is some example code to show how I am using the selectedItems property of iron-list:
<dom-module id="example-component">
<template>
<iron-list
id="dataList"
items="[[data]]"
as="item"
multi-selection
selection-enabled
selected-items="{{selectedItems}}">
<template>
<span>[[item.data]]</span>
</template>
</iron-list>
<template is="dom-repeat" items="[[selectedItems]]" index-as="index">
<div>[[item.data]]</div> <!-- this displays any selected item -->
</template>
</template>
<script>
Polymer({
is: 'example-component',
properties: {
data: {
type: Array,
value: [
{
'data': "item 0"
},
{
'data': "item 1"
}
]
},
selectedItems:
{
type: Object,
observer: '_selectedItemsChanged'
}
},
_selectedItemsChanged: function(){
console.log(this.selectedItems); //this neither runs nor outputs anything when an item is selected
}
});
</script>
From the docs:
Finally, to observe mutations to arrays (changes resulting from calls to push, pop, shift, unshift, and splice, generally referred to as “splices”), specify a path to an array followed by .splices as an argument to the observer function.
Therefore, remove the selectedItems property and add a manual observer like so:
observers: [
'_selectedItemsChanged(selectedItems.splices)'
],

AngularJS custom directive within ng-repeat with dynamic attributes and two way binding

I'm banging my head on the wall over this for days and finally decided to post this question since I can't find an answer that matches what I'm trying to do.
Context: I'm building a dynamic form building platform that describes form elements in a JSON structure like this -
{
"name": "email",
"type": "email",
"text": "Your Email",
"model": "user.profile.email"
}
And then in the View I have a recursive ng-repeat that includes the field template like this -
<script type="text/ng-template" id="field.html">
<div ng-if="field.type === 'email'" class="{{field.class}}">
<p translate="{{field.text}}"></p>
<input type="{{field.type}}" name="{{field.name}}" class="form-control" dyn-model="{{field.model}}">
</div>
</script>
As you see, I use a custom directive dynModel to create the ng-model attribute with interpolated value of the model from the string value. So far do good.
Now I have a more complex scenario in which I have a collection of fields that can be added or removed by clicking on Add button or removeMe button. See below -
{
"name": "urls",
"type": "collection",
"text": "Your Profile URLs",
"model": "user.profile.urls",
"items": [
{
"name": "url",
"type": "url",
"text": "Facebook URL",
"model": "url"
},
{
"name": "url",
"type": "url",
"text": "Facebook URL",
"model": "url"
}
],
"action_button": {
"name": "add",
"type": "action",
"action": "addURL"
}
}
<div ng-if="field.type === 'collection'">
<button class="btn btn-info" dyn-click click-action="{{field.action_button.action}}" click-model="{{field.model}}">{{field.action_button.text}}</button>
<div dyn-ng-repeat="item in {{field.model}}" >
<div ng-repeat="field in field.items" ng-include src="'field.html'"></div>
</div>
</div>
As you'll notice, I have another custom directive that takes care of interpolation of {{field.model}} from the previous ng-repeat (not shown).
Now to the crux of the issue. As you see in the template, I have nested ng-repeats, the first one iterates through user.profile.urls and the second one iterates through the field parameters in JSON and creates the HTML tags, etc. One of those fields is a button (action_button) that is used to add more URLS to the list. When I click the button, I want it to trigger a function in my controller and effectively add a new child to the parent model (user.profile.urls). I then also want each URL, existing and new to have a remove button next to them that will be dynamic and will remove that particular item from the model.
If you see the code above, I have a custom directive dyn-click that reads in the
click-action="{{field.action_button.action}}"
That contains the function name (addURL) to be called that resides in my controller and the model
click-model="{{field.model}}"
(user.profile.urls) to which the new item is to be added. This is not working. The reason for this complexity is that I have multiple levels of nesting and at each level there are dynamic elements that need to be interpolated and bound. The directive dyn-click looks like this right now -
exports = module.exports = function (ngModule) {
ngModule.directive("dynClick",function() {
return {
restrict: 'A',
link: function(scope,element,attrs) {
$(element).click(function(e, rowid){
scope.clickAction(scope.clickModel, scope.$index);
});
}
};
});
};
With this code, when I click on the rendered form's Add button, the code in the $(element).click method above gets executed giving the following error -
Uncaught TypeError: undefined is not a function
I have tried a few different things with scope:{} in the dyn-click directive, with different errors and none of them have worked completely with two way binding of the model and calling the function as expected.
Help!
EDIT-1 - please see the comments:
$(element).click(function(e, rowid){
scope.$eval(attrs["clickAction"])(scope.$eval(attrs["clickModel"]), scope.$index);
});
EDIT-2: The plunker is here - http://plnkr.co/edit/DoacjRnO61g4IYodPwWu?p=preview. Still tweaking it to get it right, but you guys should be able to see the necessary pieces. Thanks!
EDIT-3: Thanks Sebastian. The new plunker is here - http://plnkr.co/edit/Z6ViT7scubMxa17SFgtx?p=preview . The issue with the field.items ng-repeat still exists. For some reason the inner ng-repeat is not being executed. Any ideas? Josep, Sebastian?

Resources