I am facing problem with infinite loop on loading the view. The data is loaded from an API call using ngResource in the controller. The view seems to be reloaded multiple times before rendering the view correctly. I use ng directives in the template calling scope methods and this seems to get into loop causing the view to be re-rendered.
Here is my Controller
.controller('IndexCtrl', ['$scope', '$stateParams', 'ProfileInfo',
function($scope, $stateParams, ProfileInfo) {
$scope.navTitle = 'Profile Information';
$scope.data = {};
ProfileInfo.query({
id: $stateParams.id
}).$promise.then(function(Profile) {
if (Profile.status == 200) {
$scope.data.Profile = Profile.data[0];
}else{
console.log(Profile.status);
}
}, function(error) {
console.log(error);
});
$scope.showImageBlock = function(object, image) {
if (object.hasOwnProperty('type') && object.type == 'image') {
imageReference = object.value;
var imageUrl;
angular.forEach(image, function(value, key) {
if (value.id == imageReference) {
$scope.data.imageUrl = value.graphic.url;
return;
}
});
}
return object.hasOwnProperty('type') && object.type == 'image';
};
$scope.showText = function(object) {
console.log('text');
return object.hasOwnProperty('type') && object.type == 'text';
};
}
])
And Here is my template
<ion-view cache-view="false">
<ion-nav-title>
{{navTitle}}
</ion-nav-title>
<div class="bar bar-subheader bar-light">
<h2 class="title">{{navSubTitle}}</h2>
</div>
<ion-content has-header="true" padding="true" has-tabs="true" class="has-subheader">
<div ng-repeat="profileInfo in data.Profile">
<div class="list">
<img ng-if="showImageBlock(profileInfo,data.Profile.images)" ng-src="{{ data.imageUrl }}" class="image-list-thumb" />
<div ng-if="showText(profileInfo)">
<a class="item">
{{profileInfo.name}}
<span ng-if="profileInfo.description.length != 0"class="item-note">
{{profileInfo.description}}
</span>
</a>
</div>
</div>
</div>
</ion-content>
Here is the output of console window when tried log the number of times showText function is called.
The actual result from ngResource call has only 9 items in array but it loops more than 9 times and also multiple loops. This happens for a while and stops. Could anyone please point me in the right direction in fixing it.
Thank you
Finally I ended up creating a custom directive which does the function of ng-if without the watchers which triggers the digest loop. It's not a pretty solution but it seems to do the job as expected. I copied the code of ng-if and removed the $scope watcher. Here is the custom directive.
angular.module('custom.directives', [])
.directive('customIf', ['$animate',function($animate) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
value = $scope.$eval($attr.customIf);
if (value) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end customIf: ' + $attr.customIf + ' ');
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
}
else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
}
};
}]);
This allows us to use the customIf as follows
<div custom-if="showText(profileInfo)">
Related
I am working on an application that goes from template A to template B back to template A. On template A the user click on a button to get to template B. On template B the user add in an amount then hits submit. The program then goes back to template A and displays what was inputted in template B, but the number submitted is not updated in the scope and appears as null. For some reason when I start the application from Template B to Template A the scope is updated.
I am using a factory
.factory('myService', function(){
var budget = {
limit: null
};
function set(data){
budget.limit = data;
}
function get(){
return budget.limit;
}
return{
set: set,
get: get,
print: console.log(budget.limit)
}
})
Here is my code for Template A called BudgetCalc
<ion-view view-title="BudgetCalc">
<ion-content class="padding">
<button>Start Budgeting</button>
<h2>Your Limit is {{limit}}</h2>
</ion-content>
</ion-view>
And Template B named addBuget
<ion-view view-title="Add a Budget">
<ion-content>
<label class="item item-input">
<span class="input-label">Set Spending Limit</span>
<input type="number"ng-model="limit">
</label>
<button ui-sref="tab.budget" ng-click="setLimit(limit)">Submit</button>
<br><h2>Your Limit is: {{limit}}</h2>
</ion-content>
</ion-view>
Here is are my Controllers for the two templates
.controller('BudgetCtrl', function($scope, myService) {
$scope.limit = myService.get();
console.log("This is your limit " + $scope.limit);
})
.controller('SetLimitCtrl', function($scope, myService){
$scope.setLimit = function(limit){
if (limit != null) {
myService.set(limit);
console.log(myService.print);
}
}
})
You can share data between controllers using localstorage
.controller('SetLimitCtrl', function($scope, $localstorage){
$scope.setLimit = function(limit){
if (limit != null) {
$localstorage.set("limit",limit);
console.log($localstorage.get("limit"));
}
}
})
.controller('BudgetCtrl', function($scope, $localstorage) {
$scope.limit = $localstorage.get("limit");
console.log("This is your limit " + $scope.limit);
//// Dont forgot to clear limit when you complete the further process
})
Factory Localsoarage:
.factory('$localstorage', ['$window', function ($window) {
return {
set: function (key, value) {
$window.localStorage[key] = value;
},
get: function (key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
setObject: function (key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function (key, nulled) {
nulled = '[]';
try {
return JSON.parse($window.localStorage[key] || '[]');
} catch (e) {
}
},
delete: function (key) {
$window.localStorage.removeItem(key);
},
};
}])
Getting this error: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
I have created a reddit style nested comment system using AngularJS. But after 10 levels deep i get a very ugly error on my console that looks like this:
This happens after exactly 10 levels deep:
The nested comments are directives that look like this:
commentCont.tpl.html:
<div class="comment-cont">
<div
class="upvote-arrow"
ng-show="!collapsed"
ng-click="vote()"
ng-class="{'active' : node.votedByMe}"
>
<div class="upvote-arrow-top"></div>
<div class="upvote-arrow-bottom"></div>
</div>
<div class="wrapper">
<div class="info">
<span class="collapse" ng-click="collapsed = !collapsed">[ {{collapsed ? '+' : '–'}} ]</span>
<span ng-class="{'collapsed-style' : collapsed}">
<a ui-sref="main.profile({id: node.userId})">{{node.username}}</a>
<span>{{node.upvotes}} point{{node.upvotes != 1 ? 's' : ''}}</span>
<span mg-moment-auto-update="node.createdTime"></span>
<span ng-show="collapsed">({{node.children.length}} child{{node.children.length != 1 ? 'ren' : ''}})</span>
</span>
</div>
<div class="text" ng-bind-html="node.comment | autolink | nl2br" ng-show="!collapsed"></div>
<div class="reply" ng-show="!collapsed">
<span ng-click="formHidden = !formHidden">reply</span>
</div>
</div>
<div class="input-area" ng-show="!collapsed">
<form ng-show="!formHidden" name="form" autocomplete="off" novalidate ng-submit="submitted = true; submit(formData, form)">
<div class="form-group comment-input-feedback-branch has-error" ng-show="form.comment.$invalid && form.comment.$dirty">
<div ng-messages="form.comment.$error" ng-if="form.comment.$dirty">
<div class="input-feedback" ng-message="required">Comment text is required.</div>
<div class="input-feedback" ng-message="maxlength">Comment text cannot exceed 2500 characters.</div>
</div>
</div>
<div
class="form-group"
ng-class="{ 'has-error' : form.comment.$invalid && form.comment.$dirty, 'has-success' : form.comment.$valid }"
>
<textarea
name="comment"
class="textarea comment-cont-textarea"
ng-model="formData.comment"
required
ng-maxlength="2500"
textarea-autoresize
></textarea>
</div>
<div class="form-group">
<mg-button-loading
mgbl-condition="awaitingResponse"
mgbl-text="Save"
mgbl-loading-text="Saving..."
mgbl-class="btn-blue btn-small"
mgbl-disabled="!form.$valid"
></mg-button-loading>
<mg-button-loading
mgbl-text="Cancel"
mgbl-class="btn-white btn-small"
ng-click="formHidden=true;"
></mg-button-loading>
</div>
</form>
</div>
<div ng-show="!collapsed">
<div ng-repeat="node in node.children" ng-include="'commentTree'"></div>
</div>
</div>
commentCont.directive.js:
(function () {
'use strict';
angular
.module('app')
.directive('commentCont', commentCont);
/* #ngInject */
function commentCont ($http, user, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {
node: '='
},
templateUrl: 'app/post/commentCont.tpl.html',
link: function (scope, element, attrs) {
var textarea = element.querySelector('.comment-cont-textarea');
var voteOK = true;
var action = '';
var userInfo = user.get();
scope.formHidden = true; // Do not ng-init="" inside an ng-repeat.
scope.collapsed = false; // Do not ng-init="" inside an ng-repeat.
// Autofocus textarea when reply link is clicked.
scope.$watch('formHidden', function(newValue, oldValue) {
if (newValue !== true) {
$timeout(function() {
textarea[0].focus();
});
}
});
scope.submit = function (formData, form) {
if (form.$valid) {
scope.awaitingResponse = true;
formData.parentId = scope.node.id;
formData.postId = scope.node.postId;
formData.type = 4;
formData.fromUsername = userInfo.username;
formData.toId = scope.node.userId;
formData.fromImage = userInfo.thumbnail36x36.split('/img/')[1];
// console.log(formData);
$http.post('/api/comment', formData)
.then(function (response) {
scope.awaitingResponse = false;
if (response.data.success) {
if (response.data.rateLimit) {
alert(rateLimitMessage);
return false;
}
// id and createdTime is sent with response.data.comment.
var c = response.data.comment;
var newCommentNode = {
id: c.id,
userId: userInfo.id,
username: userInfo.username,
parentId: formData.parentId,
comment: formData.comment,
upvotes: 0,
createdTime: c.createdTime,
votedByMe: false,
children: [],
postId: scope.node.postId
};
// console.log('user', user.get());
// console.log('scope.node', scope.node);
// console.log('response', response);
// console.log('newCommentNode', newCommentNode);
formData.comment = '';
form.comment.$setPristine();
scope.formHidden = true;
scope.node.children.unshift(newCommentNode);
}
});
}
};
scope.vote = function() {
if (voteOK) {
voteOK = false;
if (!scope.node.votedByMe) {
scope.node.votedByMe = true;
action = 'add';
} else {
scope.node.votedByMe = false;
action = 'remove';
}
var data = {
commentId: scope.node.id,
action: action
};
$http.post('/api/comment/vote', data)
.then(function (response) {
// console.log(response.data);
voteOK = true;
if (action === 'add') {
scope.node.upvotes++;
} else {
scope.node.upvotes--;
}
});
}
};
}
};
}
}());
The tree is being called like this:
<script type="text/ng-template" id="commentTree">
<comment-cont
node="node"
></comment-cont>
</script>
<div ng-repeat="node in tree[0].children" ng-include="'commentTree'"></div>
How can I have more than 10 levels of nested ng-repeat without getting an error like this?
The default implementation of $digest() has limit of 10 iterations . If the scope is still dirty after 10 iterations error is thrown from $digest().
The below stated is one way of configuring the limit of digest iterations to 20.
var app = angular.module('plunker', [], function($rootScopeProvider) {
$rootScopeProvider.digestTtl(20); // 20 being the limit of iterations.
});
But you should look in to stabilizing your model rather than configuring the limit of iterations.
I was dealing with a similar issue. end up with the following directive:
(function () {
'use strict';
angular
.module('app')
.directive('deferDom', ['$compile', ($compile) => {
return {
restrict: 'A',
compile: (tElement) => {
// Find, remove, and compile the li.node element.
let $el = tElement.find( "li.node" );
let transclude = $compile($el);
$el.remove();
return function($scope){
// Append li.node to the list.
$scope.$applyAsync(()=>{
tElement.append(transclude($scope));
});
}
},
};
}]);
})();
I have two scope functions and when i click the button only then will any of them be called but once it is called, i realize that the value of the scope variable automatically updates each time.
$scope.images = [];
$scope.imagesAttached =[];
$scope.takePhoto = function(index) {
if(modalExists === true) {
$scope.modal1.hide();
}
$scope.showSendButton = true;
$scope.attachedImageExists = false;
if($scope.imagesAttached.length > 0) {
$scope.images = $scope.imagesAttached
$scope.attachedImageExists = true;
}
var options = {
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
correctOrientation: true
};
// 3
$cordovaCamera.getPicture(options).then(function(imageData) {
// 4
var imagetype;
onImageSuccess(imageData);
function onImageSuccess(fileURI) {
createFileEntry(fileURI);
}
function createFileEntry(fileURI) {
window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
}
// 5
function copyFile(fileEntry) {
var name = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('/') + 1);
var newName = (new Date()).getTime() + name;
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
newName,
onCopySuccess,
fail
);
}, fail);
}
// 6
function onCopySuccess(entry) {
$scope.$apply(function() {
$scope.modal.remove();
$scope.activeSlide = index;
if(modalExists === false) {
$ionicModal.fromTemplateUrl('image-modal.html', {
scope: $scope,
}).then(function(modal) {
$scope.modal1 = modal;
$scope.modal1.show();
modalExists = true;
$scope.images.push({file: entry.nativeURL, type: $scope.imagelist});
console.log($scope.imagesAttached.length)
console.log($scope.images.length)
});
}
else {
$scope.modal1.show();
$scope.images.push({file: entry.nativeURL, type: $scope.imagelist});
console.log($scope.imagesAttached.length)
console.log($scope.images.length)
}
});
}
function fail(error) {
console.log("fail: " + error.code);
}
}, function(err) {
console.log(err);
});
}
$scope.sendPhoto = function() {
$scope.imagesAttached = angular.copy($scope.images);
}
my image-modal.html page
<script id="image-modal.html" type="text/ng-template">
<div class="modal image-modal transparent">
<ion-header-bar class="bar bar-header bar-dark">
<div class ="row">
<div class ="col">
<label ng-click="closeModal(1)">Cancel</label>
</div>
<div class ="col">
<label ng-click="deleteImage()">Delete</label>
</div>
<div class ="col" id="send-images" ng-show="showSendButton">
<label ng-click="sendtoAttach()">Send</label>
</div>
</div>
</ion-header-bar>
<ion-slide-box on-slide-changed="slideChanged($index)" show-pager="true" active-slide="activeSlide" >
<ion-slide ng-repeat="image in images">
<img ng-src="{{image.file}}" class="fullscreen-image"/>
</ion-slide>
</ion-slide-box>
<div class="row">
<ion-scroll>
<img ng-repeat="image in images" ng-src="{{urlForImage(image.file)}}" class="image-list-thumb" height="50px"/>
</ion-scroll>
<button class="ion-camera" ng-click="takePhoto()"></button>
</div>
</div>
</script>
I have got two buttons Take and Send
when i call takePhoto for the first time and SendPhoto, the value is correct, one image is pushed and the length of my $scope.images and $scope.imagesAttached is 1,
But if i click takePhoto button again, without calling SendPhoto button, both my $scope.images and $scope.imagesAttached length is updated to 2 whereas it should be only $scope.images = 2 while $scope.imagesAttached = 1 since i havent called $scope.sendPhoto yet.
I know angularJS has some double binding stuff with $apply and $digest but not sure how it works and why it is auto binding my scope variables.
Any help appreciated
This has nothing to do with Angular, it is purely JavaScript object references at work.
When you assign $scope.images to $scope.imagesAttached, both variables reference the same object.
Try this instead in your sendPhoto function
$scope.imagesAttached = angular.copy($scope.images)
I'm trying to draw a morris chart in an angular directive that is within an ng-repeat block. It is weird, because it draws, almost? I can see it's there and the mouseovers work, but the graph itself is only a thin line at the top. Does anybody have any ideas?
Here's the html:
<div id="page-wrapper" ng-repeat="d in dealerGroup.Dealerships__r" ng-if="expandedDealer == d.Id">
<div class="panel-heading">Area Chart Example</div>
<div class="panel-body">
<area-chart dealership="d" chartData="d.SalesChartData"></area-chart>
</div>
</div>
And here's the directive
angular.module('areaChart', ['ui.bootstrap']).directive('areaChart', function($window) {
var directive = {};
// directive.templateUrl = directivePath + '/charts/area-chart.html';
directive.restrict = 'EA';
directive.scope = {
dealership: "=",
chartdata: "="
};
directive.controller = function($scope) {
$scope.ykeys = function() {
var ykeys = [];
angular.forEach($scope.chartdata, function(d,k) {
angular.forEach(d, function(value,key) {
if(key != 'period') { ykeys.push(key); }
})
});
return ykeys;
}
}
directive.link = function($scope,element,attrs) {
Morris.Area({
element: element,
xkey: 'period',
ykeys: $scope.ykeys(),
labels: $scope.ykeys(),
hideHover: 'auto',
pointSize: 2,
data: $scope.chartdata
});
}
return directive;
});
And here's what happens:
Additionally, resizing makes the whole thing blow up with javascript errors everywhere. But i'll worry that separately
I'm trying to access image src with controller to save it, but can not figure out how to do it.
My template:
<img data-ng-model="book.image"
style="width: 300px; height: 200px;"
ng-src="data:image/png;base64,iVBORw0K...SuQmCC">
<a data-ng-click="save(book)" class="btn">Submit</a>
My controller:
controller('BookEditController', [ '$scope', '$meteor', function ($scope, $meteor) {
$scope.save = function (book) {
if (typeof book == 'object') {
var books = $meteor("books");
var id = books.insert(book);
}
};
}])
One option is using a directive and applying a method called save to it which would handle the src attribute found on the image tag.
JS
var app = angular.module('myApp', []);
app.directive('saveImage', function () {
return {
transclude: true,
link: function (s, e, a, c) {
s.save=function(){
alert(a.src);
};
}
};
});
HTML
<div >
<img save-image style="width: 300px; height: 200px;" src="http://placehold.it/350x150"> <a ng-click="save()" class="btn">Submit</a>
</div>
This is the code implemented in jsfiddle.
Another option is to isolate the scope to a controller but still apply the image to it instead of a function.
JS
var app = angular.module('myApp', []);
app.directive('saveImage', function () {
return {
transclude: true,
link: function (s, e, a, c) {
s.image = a.src;
}
};
});
function cntl($scope) {
$scope.save = function (img) {
alert($scope.image || 'no image');
}
}
HTML
<div ng-controller='cntl'>
<img save-image style="width: 300px; height: 200px;" src="http://placehold.it/350x150"> <a ng-click="save()" class="btn">Submit</a>
</div>
Notice the added ng-controller="cntl".
This is the JSfiddle for that one.
There's probably a better way to do this... pass $event to your controller function
<a data-ng-click="save(book, $event)" class="btn">Submit</a>
and then use traversal methods to find the img tag and its src attr:
$scope.save = function (book, ev) {
console.log(angular.element(ev.srcElement).parent().find('img')[0].src);
...
Update: the better way is to create a directive (like #mitch did), but I would use = binding in an isolate scope to update a src property in the parent scope. (The = makes it clear that the directive may alter the scope. I think this is better than having a directive add a method or a property to the controller's scope "behind the scenes".)
<div ng-controller="MyCtrl">
<img save-image book="book1" src="http://placehold.it/350x150" >
Submit
</div>
function MyCtrl($scope) {
$scope.book1 = {title: "book1" }; // src will be added by directive
$scope.save = function(book) {
alert(book.title + ' ' + book.src);
}
}
app.directive('saveImage', function () {
return {
scope: { book: '=' },
link: function (s, e, a, c) {
s.book.src = a.src;
}
};
});
Plunker