AngularJS: How to prevent recursive templating from looping forever - javascript

I've written a set of code which, when bound to an object, will display the key and value of every property in that object.
<script type="text/ng-template" id="object-displayer">
<div ng-if="recurrable(value)">
<span class="recurrable">
<span class="key">{{key}}</span>
(<span class="type" ng-bind="type(value)"></span>)
</span>
<ul class="indent">
<li ng-repeat="(key, value) in value track by $index" ng-include="'object-displayer'"></li>
</ul>
</div>
<div ng-if="!recurrable(value)">
<span class="primitive">
<span class="key">{{key}}</span> (<span class="type" ng-bind="type(value)"></span>): <span class="value">{{value}}</span>
</span>
</div>
</script>
And within the controller:
$scope.recurrable = function (value) {
return typeof value === 'object';
}
$scope.type = function (value) {
return typeof value;
}
jsbin: (https://jsbin.com/xusiteluwi/1/edit?html,js,output)
This works great when your nested objects create a simple tree structure. But it throws an exception when you create a loop: if one of your properties references any object upstream, it will display until the digest limit is reached (usually 10).
Now here's my question. Is there some way in angular controller/templating to ng-if whether an object has already been shown, thus catching any loops and displaying only a single iteration?
Bonus points if you can come up with a solution that will apply globally in the graph, or a solution that will only track the current branch.

Start with an empty visitedReferences.
Each time you encounter any reference (object) check if it is in the visitedReferences and if so don't follow this reference, otherwise add it to the visitedReferences.

Hope Help You!
angular
.module('test', [])
.controller('RecursiveCtrl', function($scope) {
var vm = $scope;
vm.data = {
a: 'Hello',
b: {
c: 'World'
}
};
vm.isRecursive = function(value) {
return angular.isObject.call(this, value);
};
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<article data-ng-app="test">
<div data-ng-controller="RecursiveCtrl">
<script type="text/ng-template" id="tpl-recursive">
<div ng-switch="isRecursive(value)">
<div ng-switch-when="false" >
<strong ng-bind="prop"></strong>: <span ng-bind="value"></span>
</div>
<div ng-switch-when="true">
<ol>
<li ng-repeat="(prop, value) in value" ng-include="'tpl-recursive'">
</li>
</ol>
</div>
</div>
</script>
<ol>
<li ng-repeat="(prop, value) in data" ng-include="'tpl-recursive'"></li>
</ol>
</div>
</article>

Related

match parent and inner index within nested ng-repeats while passing duplicate values

I am trying to pass duplicate values in different formats but can not match parent and inner indexes hence I get Error: [ngRepeat:dupes]. that said, I pass object with multiple properties among which I have tags...see below
vm.hotels returns objects like below
0:object
tags:"tag1|tag2|tag3"
1:object
tags:"tag1|tag2|tag3"
vm.hTags is an array that matches each object like below
["tag1", "tag2", "tag3"]
within my controller I split tags and push then into an array within a loop which I pass to the view. this works as it should but I can not make it work with indexes within the view. below are nested ng-repeats
<li ng-repeat="item in vm.hotels track by $index">
<ul>
<li ng-repeat="tag in vm.hTags[$index]">
{{tag}}
</li>
</ul>
<li>
I tried to use vm.hTags[$parent.$index] but it does not work as duplicate error is thrown due to indexes. Perhaps I need to create some custom tracking property ?
The problem with nested ng-repeat is that is that if you use $index for both child and parent, it might conflict. In order to avoid it, we can use it by giving name. Like this
ng-repeat="(hotelIndex, item) in vm.hotels ..."
I don't know how you want to render it but here's a sample example of that:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.hotels = [{
tags: "tag1|tag2|tag3"
}, {
tags: "tag4|tag5|tag6"
}]
vm.hTags = [["tag1", "tag2", "tag3"], ["tag4", "tag5", "tag6"]]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="MainCtrl as vm">
<div ng-repeat="(hotelIndex, item) in vm.hotels track by hotelIndex">
<div ng-repeat="tag in vm.hTags[hotelIndex]">
{{tag}}
</div>
<br>
</div>
</body>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.hotels = [{
tags: "tag1|tag2|tag3"
}, {
tags: "tag4|tag5|tag6"
}]
vm.hTags = [["tag1", "tag2", "tag3"]];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<body ng-app="myApp" ng-controller="MainCtrl as vm">
<div ng-repeat="key in vm.hotels">
<div ng-repeat="tag in vm.hTags[$index]">
{{tag}}
</div>
</div>
<br>
<div ng-repeat="(key, value) in vm.hotels">
<div ng-repeat="tag in vm.hTags[key]">
{{tag}}
</div>
</div>
</body>
Please find the code change below,
<li ng-repeat="item in vm.hotels track by $index">
<ul>
<li ng-repeat="tag in vm.hTags[$index]">
{{tag}}
</li>
</ul>
<li>
Check and let me know.You made a syntax error

Angular: Async push to recursively generated array

A quick explanation: this is a simple app meant to recreate Reddit, so each comment on a post (which I'm calling a "node") contains an array of comments (nodeList), and each comment can have any number of nodes in this list. What I want to do is push an added comment into the current ng-repeat object's "nodeList", so that I can add the comment without refreshing.
This recursive template works, but only when I refresh the page, so it isn't being pushed into the current scope of the ng-repeat. I've done some research about $index, but because it's recursively generated there is no way of knowing how deep down the tree of nested arrays you could be.
What I tried was $scope.x.nodeList = [] and then pushing a new "node" into that, thinking that each instance of "x" is a new $scope within the ng-repeat, but this is not working.
Controller:
redditLite.controller('post', function($routeParams, $scope, $http) {
var postId = $routeParams.id;
var controller = this;
var postComment = {};
var node = {};
$scope.show = true;
$scope.addComment = {};
$scope.post = {};
$scope.x = {};
$scope.x.nodeList = [];
controller.comment = function(parentId) {
postComment.comment = $scope.addComment.body;
postComment.parentId = parentId;
postComment.rootPostId = $scope.post.id;
$http.post('add-comment',postComment, config).then(function(response) {
node = response.data;
$scope.x.nodeList.push(node);
});
}
});
HTML:
<script type="text/ng-template" id="postTree">
<div class="username">
{{x.username}}
</div>
<div class="body">
{{x.body}}
</div>
<div class="metrics">
<ul>
<li>
Likes: {{x.likes}}
<br>
<button class="like-button" ng-click="controller.likeNode(x.nodeId); x.likes = x.likes + 1">Like</button>
</li>
<li>
Comments: {{x.cmmnts}}
<br>
<button class="comment-button" ng-click="show = !show" ng-show="show">Comment!</button>
<div class="comment-field" ng-hide="show">
<input type="text" placeholder="Enter a comment." ng-model="addComment.body">
<br>
<button ng-click="controller.comment(x.nodeId); show = !show">Submit</button>
<br>
<button ng-click="show = !show">Cancel</button>
</div>
</li>
<li>
Date: {{x.submit_date}}
</li>
</ul>
</div>
<div class="nodes">
<ul ng-if="x.nodeList" ng-model="x.nodeList">
<li ng-repeat="x in x.nodeList" ng-include="'postTree'"></li>
</ul>
</div>
</script>
<div class="post">
<div class="username">
{{post.username}}
</div>
<div class="body">
{{post.body}}
</div>
<div class="metrics">
<ul>
<li>
Likes: {{post.likes}}
<br>
<button class="like-button" ng-click="controller.like(post.id); post.likes = post.likes + 1">Like</button>
</li>
<li>
Comments: {{post.cmmnts}}
<br>
<button class="comment-button" ng-click="show = !show" ng-show="show">Comment!</button>
<div class="comment-field" ng-hide="show">
<input type="text" placeholder="Enter a comment." ng-model="addComment.body">
<br>
<button ng-click="controller.comment(post.id); show = !show">Submit</button>
<br>
<button ng-click="show = !show">Cancel</button>
</div>
</li>
<li>
Date: {{post.submit_date}}
</li>
</ul>
</div>
</div>
<ul class="master-list">
<li ng-repeat="x in post.nodeList" ng-include="'postTree'"></li>
</ul>
There is some missing logic that needs to be handled, but for now I'm trying to get this working to push an object into an array no matter how deeply nested that array is within other objects.
Edit: I've included an image of the JSON structure as a referencece, and it can be seen that each node object can contain an array of node objects, so this is the array that I am attempting to push a new node into.
I've done recursive templating like this successfully several times. If I recall, having the ng-repeat and ng-include on the same html tag is problematic. Try wrapping the contents of your script in a div, remove the ng-include attribute from your li elements, and instead add an ng-include element inside of your li elements. Also, you have basically added your template twice, once for the root item, then again to add recursive behavior. You should be able to only have 1 template (the script one) if you wrap your post variable inside of an array in your markup.
<script type="text/ng-template" id="postTree">
<div>
...
<div class="nodes">
<ul ng-if="x.nodeList" ng-model="x.nodeList">
<li ng-repeat="x in x.nodeList">
<ng-include src="'postTree'"></ng-include>
</li>
</ul>
</div>
</div>
</script>
<ul class="master-list">
<li ng-repeat="x in [ post ]">
<ng-include src="'postTree'"></ng-include>
</li>
</ul>
Update:
When comment is clicked, send the parent to the function instead of just the parent id. This way, you can push the child onto it's parent after the $http post completes.
JS:
angular
.module('redditLite', [])
.controller('post', function($scope, $http) {
var controller = this;
$scope.show = true;
$scope.post = {
id: 1,
parentId: null,
username: 'jeff',
body: 'my fantastic comment',
likes: 152,
submit_date: new Date(),
nodeList: []
};
$scope.comment = function(parent) {
var postComment = {
id: 2,
parentId: parent.id,
username: 'jeff',
body: parent.addComment,
likes: 0,
submit_date: new Date(),
nodeList: []
};
console.log('adding comment', postComment, parent)
$http.post('add-comment',postComment, config).then(function(response) {
var node = response.data;
parent.nodeList.push(node);
});
}
});
HTML
<script type="text/ng-template" id="postTree">
<div>
<div class="username">
{{x.username}}
</div>
<div class="body">
{{x.body}}
</div>
<div class="metrics">
<ul>
<li>
Likes: {{x.likes}}
<br>
<button class="like-button" ng-click="controller.likeNode(x.nodeId); x.likes = x.likes + 1">Like</button>
</li>
<li>
Comments: {{x.nodeList.length}}
<br>
<button class="comment-button" ng-click="show = !show" ng-show="show">Comment!</button>
<div class="comment-field" ng-hide="show">
<input type="text" placeholder="Enter a comment." ng-model="x.addComment">
<br>
<button ng-click="comment(x); show = !show">Submit</button>
<br>
<button ng-click="show = !show">Cancel</button>
</div>
</li>
<li>
Date: {{x.submit_date}}
</li>
</ul>
</div>
<div class="nodes">
<ul ng-if="x.nodeList" ng-model="x.nodeList">
<li ng-repeat="x in x.nodeList">
<ng-include src="'postTree'"></ng-include>
</li>
</ul>
</div>
</div>
</script>
<ul class="master-list">
<li ng-init="x = post">
<div ng-include="'postTree'"></div>
</li>
</ul>
Plunker:
https://plnkr.co/edit/X40JoHduKYy12QPuLBCo?p=preview
You might be getting hurt by lexical scope. Basically:
$http.post('add-comment',postComment, config).then(function(response) {
node = response.data;
$scope.x.nodeList.push(node); //this $scope is not actually your $scope
});
Try doing:
var vm = this;
$http.post('add-comment',postComment, config).then(function(response) {
node = response.data;
vm.$scope.x.nodeList.push(node); //should be the right scope.
})
If this doesn't work, try double checking your bindings. A value not updating normally means the binding is not correct.
Try using $scope.x.nodeList.concat([node]); instead of pushing the value, like this avoid mutations in the object.

Ng-click changing key,value pair

I have a ng-repeat like this:
<div ng-app="myApp" ng-controller="Ctrl">
{{ctrlTest}}<hr/>
<div ng-repeat="elements in filter">
<div>
<li ng-repeat="(key,value) in filter.producers" ng-show="value">
{{key}}<a ng-click="filter.producers.key=false"> X</a>
</li>
</div>
{{filter.producers}}
</div>
angular.module('myApp', [])
.controller('Ctrl', function($scope) {
$scope.ctrlTest = "Filters";
$scope.filter = {"producers": {"Ford":true,"Honda":true,"Ferrari":true}}
});
I am trying to make a ng-click that would set each label to false when clicking in a link, but I haven't achieved to do it properly as the key values are not fixed (they should be treated as variables).
So far I have tried it his way.
http://jsfiddle.net/Joe82/wjz8270z/5/
Thanks in advance!
Ps: I cannot change the json structure.
You just need to access the element of object by its key, to ensure that there references would not get lost & binding will work
<li ng-repeat="(key,value) in filter.producers" ng-show="value">
{{key}}<a ng-click="filter.producers[key]=false"> X</a>
</li>
Forked Fiddle
You also call a function and set value false
HTML
<li ng-repeat="(key,value) in filter.producers" ng-show="value">{{key}} {{value}}<a ng-click="setValue(key)"> X</a>
JS
$scope.setValue = function(key){
$scope.filter.producers[key.toString()] = false;
}
see this link http://jsfiddle.net/wjz8270z/8/

How to ng-style one element it's $index created by ng-repeat?

I have 2 directives: wa-hotspots & wa-tooltips.
On ng-mouseover of wa-hotspots it takes that $index of wa-hotspot and sets the visibility and position of wa-tooltip via ng-class:on and ng-style="tooltipCoords" by matching indexes.
Note: Since wa-hotspots & wa-tooltips share the same collection page.hotspots and therefore they share teh same index via ng-repeat
Problem:
When you hover over wa-hotspots it sets the ng-style position to ALL of the elements in wa-tooltips. I only want it ot set the proper matching index. Since the visiblity is controlled by ng-class, This doesn't really matter but it seems like it's extra overhead that could be avoid.
Therefore:
Question:
How can I make sure that my ng-style isn't styling all the wa-tooltips on hover of wa-hotspots? But rather, style only the tooltip that matches the proper shared index?
<ul id="wa-page-{{page.pageindex}}" class="wa-page-inner" ng-mouseleave="pageLeave()">
<li wa-hotspots
<map name="wa-page-hotspot-{{page.pageindex}}">
<area ng-repeat="hotspot in page.hotspots"
class="page-hotspot"
shape="{{hotspot.areashape}}"
coords="{{hotspot.coordinatetag_scaled}}"
ng-mouseover="showTooltip($index, hotspot.coordinatetag_scaled)"
ng-mouseout="hideTooltip()">
</map>
</li>
<li class="tooltip-wrapper">
<ul class="tooltip">
<li wa-tooltips
ng-repeat="hotspot in page.hotspots"
ng-class="{on: hovered.index == $index}"
ng-mouseover="hovered.active == true"
ng-mouseout="hovered.active == false"
ng-style="tooltipCoords" hotspot="hotspot">
</li>
</ul>
</li>
</ul>
tooltip:
You need to make it per item like in your case - hotspot.tooltipCoords then set that variable by index.
you can do the check inside the expression function.
Heres a fiddle
<div ng-controller="MyCtrl">
<div ng-repeat="item in items" ng-style="isChecked($index)">
name: {{item.name}}, {{item.title}}
<input type="checkbox" ng-model="item.checked" />
</div>
</div>
...
$scope.isChecked = function($index){
var color = $scope.items[$index].checked ? 'red' : 'blue';
return {color:color};
}
Instead of
ng-mouseover="hovered.active == true"
ng-mouseout="hovered.active == false"
use
ng-mouseover="hotspot.class== 'active'"
ng-mouseout="hotspot.class== ''"
and after that you can use hotspot.class in ng-class ie:
ng-class="hotspot.class"
Please see demo below:
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
$scope.items = [{
id: 1
}, {
id: 2
}, {
id: 3
}, {
id: 4
}]
});
.red {
background-color: yellow;
}
p {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<p ng-repeat="i in items" ng-mouseover="i.class='red'" ng-class="i.class" ng-mouseout="i.class = ''">{{i.id}}</p>
</div>
</div>
Use the below one
<div class="col-md-4 col-xs-12 col-lg-4" ng-repeat="obj in items">
<button type="button" class="btn btn-sm pull-right" ng-class="obj.class" ng-click="obj.class='test'" >
Write a new class "test". Instead of click you can use the same in ngmouseover

KnockoutJS - foreach not working with a single entry in viewmodel

I have the following code that, on a successful AJAX return, displays a popup window with a list of addresses. The knockout version is 2.3.0.
If there is more than 1 address then the html correctly renders with a 'display' string.
The problem is that if there is ONLY 1 address the html list renders but without any text in the span.
In both cases the view model is correctly being populated with data so it looks to me like a problem updating the html.
I have tried pushing the data again and although I can use jQuery to update the html but this doesn't help me understand the problem.
HTML
<div id="reverseGeocodingResults">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Local Addresses</h4>
</div>
<div>
<ul data-bind="foreach: vm.reverseGeocodingViewModel.AddressList" class="locationList">
<li class="locationListItem" data-bind="click: SubmitAddressRequest">
<div>
<span data-bind="text: Display"></span>
</div>
</li>
</ul>
</div>
</div>
</div>
Javascript (from a separate file so only taken what I think is relevant)
var vm;
var masterViewModel = function () {
this.viewModel = { LocationList: ko.observableArray([]), SubQuery: ko.observable() };
this.reverseGeocodingViewModel = { AddressList: ko.observableArray([]) };
};
function SubmitReverseGeocodingRequest(easting, northing, projectId, mouseLocation) {
$.post('url?action=ReverseGeocodingLookup', {
easting: easting,
northing: northing,
pid: projectId
})
.done(function (data) {
spinner.stop();
if (parseInt(data.NumberOfAddressesFound) > 0) {
if (data.AddressList.length == 1) {
alert('just 1 address');
}
// remove all array items before adding new
// Not pretty but gets around an issue the UI seems to have displaying the updated list
if (vm.reverseGeocodingViewModel.AddressList().length > 0) {
vm.reverseGeocodingViewModel.AddressList.splice(0, vm.reverseGeocodingViewModel.AddressList().length);
}
vm.reverseGeocodingViewModel.AddressList(data.AddressList);
}
});
)
$(document).ready(function () {
vm = new masterViewModel();
ko.applyBindings(vm);
})
HTML Result - Multiple Results
<ul class="locationList" data-bind="foreach: vm.reverseGeocodingViewModel.AddressList" style="height: 265px;">
<li data-bind="click: SubmitAddressRequest" class="locationListItem">
<div>
<span data-bind="text: Display">Yates Wine Lodge, SWINDON</span>
</div>
</li>
<li data-bind="click: SubmitAddressRequest" class="locationListItem">
<div>
<span data-bind="text: Display">The Brunel Centre, SWINDON</span>
</div>
</li>
</ul>
HTML Result - Single Result
<ul class="locationList" data-bind="foreach: vm.reverseGeocodingViewModel.AddressList" style="height: 265px;">
<li class="locationListItem" data-bind="click: SubmitAddressRequest">
<div>
<span data-bind="text: Display"></span>
</div>
</li>
</ul>
I have looked at various previous questions on this topic and couldn't come up with an answer hence the question, but please point me to another post if I have missed one.
to remove all before add new use reverseGeocodingViewModel.AddressList.removeAll()
Maybe didn't find it but you have to parse data, $.parseJSON I use for this.
Try to use
$.each($.parsejSON(data), function(i, el){
reverseGeocodingViewModel.AddressList.push(el);
})
I hope it will help you
I've noticed following issues:
function SubmitReverseGeocodingRequest should be closed with } not )
foreach: vm.reverseGeocodingViewModel.AddressList should be foreach: reverseGeocodingViewModel.AddressList, without vm because vm is already binded
vm = new masterViewModel();
ko.applyBindings(vm);
To clean AddressList use vm.reverseGeocodingViewModel.AddressList([]) instead vm.reverseGeocodingViewModel.AddressList.splice(0, vm.reverseGeocodingViewModel.AddressList().length);
Note: Here's possible mistake
<li class="locationListItem" data-bind="click: SubmitAddressRequest">
so AddressList item have to have the SubmitAddressRequest function. I don't think that you get data with the function
I've created test sample based on your code, take a look here

Categories

Resources