Getting "Error: [$rootScope:infdig] 10 $digest() iterations reached" message - angularjs

I want to display http response (JSON response) on html page in a table. To achieve this I wrote below controller function.
$scope.getSensorInfo=function(){
var strippeddata = [];
$http({
method: "GET",
url: "http://xx.xx.xx.xx:4000/config",
params: {did: $scope.cid}
}).then(function (success) {
if (success.data[0] === undefined) { //no device is available with this id
$http({
method: "GET",
url: "http://xx.xx.xx.xx:4000/info"
}).then(function(success1){
$scope.sinfo = success1.data;
},function(error1){
console.log('Error ' + JSON.stringify(error1));
});
} else {
Object.getOwnPropertyNames(success.data[0].obj).forEach(function (item, idx, list) {
Object.defineProperty(strippeddata, idx, {
enumerable: true,
configurable: true,
get: function () {
return {
name: item,
periodicity: success.data[0].obj[item].periodicity,
}
}
});
});
$scope.sinfo = strippeddata;
}
}, function (error) {
console.log('Error ' + JSON.stringify(error));
});
}
My html code is as follows.
<div class="row">
<div class="form-inline form-group">
<div class="col-md-3">
<label for="cnfdeviceid">Device ID</label>
<input class="form-control input-md" type="text" id="cnfdeviceid" placeholder="e.g. HYD01" ng-model="confdeviceid" ng-blur="getSensorInfo()"/>
</div>
</div>
</div>
<div ng-repeat="y in sinfo" class="[ form-group form-inline ]">
<input class="form-control input-md" type="checkbox" id="{{y.name}}" ng-model="name" ng-change="verify(y.name,y.periodicity,y.formula,name,$index)" autocomplete="off"/>
<div class="[ btn-group ]">
<label for="{{y.name}}" class="[ btn btn-success ]">
<span class="[ glyphicon glyphicon-ok ]"></span>
<span> </span>
</label>
<label for="{{y.name}}" class="[ btn btn-default active ]">
{{y.name}}
</label>
</div>
<input class="form-control input-md" type="text" ng-model="y.periodicity" placeholder="periodicity" id="{{y.periodicity}}" autocomplete="off"/>
</div>
When I am executing this code I am getting $digest 10 iterations reached aborting error. The following line is causing the problem but I am unable to rectify it.
$scope.sinfo = strippeddata;

Changing $scope.sinfo = strippeddata; to $scope.sinfo = strippeddata.slice(); resolved the issue.

Related

ng-file upload not sending file along with other data

i am using angular js frontend along with ng-file module and laravel backend, and for some reason unknown, ng fileupload doesn't send file along with other form data:
here is my form:
<form method="post" name="myForm">
<div class="form-group has-feedback">
<input type="file" ngf-select ng-model="picFile" name="file"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<i ng-show="myForm.file.$error.required">*required</i><br>
<i ng-show="myForm.file.$error.maxSize">File too large
{{errorFile.size / 1000000|number:1}}MB: max 2M</i>
<img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb"> <button ng-click="picFile = null" ng-show="picFile">Remove</button>
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" id="username" type="text" name="username" ng-model="user.username" placeholder="Name"
required
ng-minlength="6"
autofocus>
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" type="email" id="email" name="email" ng-model="user.email" placeholder="Email" required>
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" type="text" id="firstname" name="firstname" ng-model="user.firstname" placeholder="First Name">
</div>
<div class="form-group has-feedback">
<input class="form-control input-lg" type="text" id="lastname" name="lastname" ng-model="user.lastname" placeholder="Last Name">
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary" ng-disabled="!myForm.$valid" ng-click="updateProfile(picFile)" >Update</button>
<span class="progress" ng-show="picFile.progress >= 0">
<div style="width:{{picFile.progress}}%"
ng-bind="picFile.progress + '%'"></div>
</span>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
{{picFile}}
</form>
and here is my controller:
$scope.getProfile = function() {
Account.getProfile()
.then(function(response) {
$scope.user = response.data;
})
.catch(function(response) {
toastr.error(response.data.message, response.status);
});
};
$scope.updateProfile = function(file) {
file.upload = Upload.upload({
url: '/kilo/api/me',
data: {username: $scope.user.username, file: file },
method:"POST"
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data.message;
console.log(file.result);
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
};
the above sends only the "username" and leaves the file. please can anyone show me what am doing wrong?
Add arrayKey: '', headers: { 'Content-Type': undefined }, to your upload object.

Angular js Update a div without updating the whole page

Please i want to update a specific div in my view instead of reloading the whole page.
This is my Script.
$scope.submitComment = function() {
$http({
url: "comment",
method: "POST",
data: $.param($scope.commentData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
console.log(response);
$scope.loading = true;
//location.reload();
$scope.loading = false;
}).error(function(response) {
console.log(response);
alert('Sorry an error occured');
});
};
This is my view
<div ng-controller="myController">
<br> <br> <br> <br>
<form ng-submit="submitComment()" id="form">
<div class="form-group">
<label for="author">Author: </label>
<input id="author" class="form-control " type="text" ng-model="commentData.author" name="author" placeholder="Enter author">
</div>
<div class="form-group">
<label for="message">Message:</label> #{{ commentData.message }}
<textarea id="message" class="form-control" ng-model="commentData.message" name="message" placeholder="Enter Comment" rows="8" cols="40"></textarea>
</div>
<div class="form-group pull-right">
<button type="submit" class="btn btn-primary"><i class="fa fa-comment-o"> Comment</i></button>
<!-- <input class="btn btn-primary" type="submit" value="Comment"> -->
</div>
</form>
<h2>Comments</h2> <hr>
<div ng-repeat="comment in comments">
<div><strong>#{{ comment.author }}</strong></div>
<div>#{{ comment.message }} <button type="button" ng-click="deleteComment(comment.id)" class="btn btn-danger-outline btn-sm" id="submit">Delete</button></div>
<br>
</div>
</div>
I want to update my form so that the text in it goes. and also update my comments as well. I need a help on this please.
In your $scope.submitComment() method, $http.success(), you need to $scope.comments.push($scope.commentData) and you should be good to go.
$scope.submitComment = function() {
$http({
// ...
}).success(function(response) {
$scope.comments.push($scope.commentData);
});
};

Parsley Remote validation is not preventing form submission

I am using Parsley Remote validation with angularJS..using the async validator with add new user form is working fine, it uses the API and checks if the user name is already existed, and the email as well, if the user name is there it returns a 200 status, which is not equal to 404 and an error message appears.. BUT when submitting the form, if I check the form.isvalid status it returns true, it is only validating the NON remote options. I am stuck there.
here is the web form
<form class="form-horizontal form-label-left" method="post" id="AddUserForm"
data-ui-jq="parsley"
data-parsley-remote
data-parsley-priority-enabled="false"
novalidate="novalidate">
<fieldset>
<legend>
By default validation is started only after at least 3 characters have been input.
</legend>
<div class="form-group">
<label class="control-label col-sm-3" for="basic">User Name</label>
<div class="col-sm-9">
<input type="text" name="userName" class="form-control" data-ng-model="user.userName" value=""
data-parsley-remote
data-parsley-remote-validator='checkusername'
data-parsley-trigger="focusout"
data-parsley-remote-message="User name is already registerd in the system"
required="required" />
<span class="help-block">
Username must be unique
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="email">
E-mail
</label>
<div class="col-sm-9">
<input type="email" id="email" name="email" class="form-control" data-ng-model="user.email"
data-parsley-remote
data-parsley-remote-validator='checkemail'
data-parsley-trigger="focusout"
data-parsley-remote-message="Email is already registerd in the system"
required="required" />
<span class="help-block">
Email must be unique
</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-3" for="password">
Password:
</label>
<div class="col-sm-9">
<input type="password" id="password" name="password" class="form-control mb-sm" data-ng-model="user.password"
data-parsley-trigger="change"
data-parsley-minlength="6"
required="required" />
<input type="password" id="password-r" name="password-r" class="form-control" placeholder="Confrim Password" data-ng-model="user.confirmPassword"
data-parsley-trigger="change"
data-parsley-minlength="6"
data-parsley-equalto="#password"
required="required" />
</div>
</div>
</fieldset>
<div class="form-actions">
<button type="submit" data-ng-click="AddNewUser($event)" class="btn btn-danger btn-rounded pull-right">Validate & Submit</button>
<button type="button" class="btn btn-default btn-rounded">Cancel</button>
</div>
</form>
and this is my async validator:
window.ParsleyExtend = {
asyncValidators: {
checkusername: {
fn: function (xhr) {
console.log($('[name="userName"]'));
return 404 === xhr.status;
},
url: authService.serviceBase + 'api/account/CheckUserName/' //+ $('[name="userName"]').text()
},
checkemail: {
fn: function (xhr) {
console.log($('[name="email"]'));
return 404 === xhr.status;
},
url: authService.serviceBase + 'api/account/CheckEmail/'// + $('[name="email"]').text()
}
}
};
and this is how I validate the form:
$scope.AddNewUser = function ($event) {
$event.preventDefault();
//THis resturns true allways when the remote validation is not valid,, but when other non remote valdiation happens is works fine
$('#AddUserForm').parsley().validate();
//and this if statement resturns true allways even when the remote validation is not valid,, but when other non remote valdiation happens is works fine
if ($('#AddUserForm').parsley().isValid()) {
authService.saveRegistration($scope.user).then(function (response) {
$scope.savedSuccessfully = true;
// $scope.message = "User has been registered successfully, you will be redicted to login page in 2 seconds.";
//startTimer();
},
function (response) {
var errors = [];
for (var key in response.data.modelState) {
for (var i = 0; i < response.data.modelState[key].length; i++) {
errors.push(response.data.modelState[key][i]);
}
}
$scope.message = "Failed to register user due to:" + errors.join(' ');
});
}
};
just found the answer.. I have to use asyncIsValid() and asyncValidate() along with the normal isValid() and Validate() methods.. so the code will be as follows:
$('#AddUserForm').parsley().asyncValidate();
if($('#AddUserForm').parsley().isValid() && $('#AddUserForm').parsley().isAsyncValid()) {
....}
I first check each field to make sure it is validated, if a field is not validated, my ok variable will be set to false.
Here is some sample code:
$(function() {
var ok;
$('#signup').parsley().on('field:validated', function() {
ok = $('.parsley-error').length === 0;
})
.on('form:submit', function() {
if (ok) return true;
else return false;
});
});
Parsley.addAsyncValidator('checkExists', function(xhr) {
return false === xhr.responseJSON;
}, '/data-management/verify-data?filter=signup');

Firebase angularfire child.$asObject give properties undefined

I've got this code:
factory
app.factory('Items', function($firebase,FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL);
var items = $firebase(ref.child('items')).$asArray();
var Item = {
all: function () {
return items;
},
create: function (item) {
return items.$add(item);
},
get: function (itemId) {
return $firebase(ref.child('items').child(itemId)).$asObject();
},
update: function (itemId, item) {
return $firebase(ref.child('items').child(itemId)).update(item);
},
delete: function (item) {
return items.$remove(item);
}
};
return Item;
});
route
app.config(function($stateProvider) {
$stateProvider
.state('items_update', {
url: '/items/update/:id',
templateUrl: 'views/items/form.html',
controller:'ItemsUpdateController',
resolve:{
item:function(Items,$stateParams){
return Items.get($stateParams.id);
}
}
})
});
controller
app.controller('ItemsUpdateController', function ($scope, item, $state) {
$scope.item = item;
console.log($scope.item.url);
$scope.add = function() {
Items.update($scope.item).then(function () {
$state.transitionTo('items');
});
}
});
why console.log($scope.item.url); give me undefined ?
but in the view I've got all the data
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()">
<div class="form-group">
<input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback />
</div>
<div class="form-group">
<input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback />
</div>
<div class="form-group">
<input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback />
</div>
<div class="form-group">
<button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button>
<input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" />
</div>
<div class="form-group form-no-required clearfix">
<div class="pull-right">
<button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button>
</div>
</div>
</form>
ENDS UP
as in the #Frank van Puffelen comment
I worked it out with:
app.controller('ItemsUpdateController', function($scope, item, $state) {
item.$loaded().then(function(data) {
$scope.item = data;
console.log($scope.item.url);
});
$scope.add = function() {
Items.update($scope.item).then(function() {
$state.transitionTo('items');
});
}
});
This is because by the time your console.log($scope.item.url); runs, the data hasn't been loaded from Firebase yet. Angular listens for a notification from Firebase/AngularFire to know when the data has loaded and then updates the view.
Also see angularfire - why can't I loop over array returned by $asArray? and Trying to get child records from Firebase.

How to $http.post with payload in data?

How do I post data from a form in AngularJS?
<form data-ng-submit="doSomething()">
<input type="text" data-ng-input="do_obj.text"/>
<input type="email" data-ng-input="do_obj.email"/>
<input type="submit" value="Do something"/>
</form>
$scope.doSomething = function () {
$http({url: '/api/oauth2/register', method: 'POST', data: $scope.do_obj}
).then(function (data, status, headers, config) {
$log.info("data = ", data, "status = ", status,
"headers = ", headers, "config = ", config);
}
);
};
Plnkr (bootstrap styled)
See plunker code here
Changed data-ng-input into data-ng-model and updated data-ng-submit to pass in the model into the scope controller for processing.
HTML:
<body data-ng-app>
<div data-ng-controller="DoCtrl" class="container" style="margin: 15px">
<form data-ng-submit="doSomething(do_obj)" role="form" class="form-inline">
<div class="form-group">
<input type="text" data-ng-model="do_obj.bar"
placeholder="Enter text"
/>
</div>
<div class="form-group">
<input class="form-group" type="email"
data-ng-model="do_obj.email"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<input class="btn btn-lg" type="submit"
data-ng-class="{'btn-info': hover}"
data-ng-mouseenter="hover = true"
data-ng-mouseleave="hover = false"
value="Do something"
/>
</div>
</form>
</div>
</body>
The syntax for posting is $http.post({url}, {payload});. I have updated your controller function to take in a parameter to pass to the post.
Controller code:
function DoCtrl($scope, $http, $log) {
$log.info("In DoCtrl");
$scope.do_obj = {};
$scope.doSomething = function (data) {
$http.post('/api/oauth2/register', data)
.success(function(successData){
console.log(successData);
});
}
}

Resources