Angular Js $scope.$apply doesn't work - javascript

I have a form through which i am adding the data. Same is the case for data update. I populate form by getting data against a particular id via $http post. I have changed the scope variables but not getting modified values. Here are my efforts :
<input type="hidden" name="form_type" ng-model="formData.formType" ng-init="formData.formType = submit_button" value="{{submit_button}}"/>
<input type="hidden" name="student_id" ng-model="formData.studentId" ng-init="formData.studentId = student_id" value="{{student_id}}"/>
$scope.Edit = function (id) {
$http({
method: 'POST',
url: 'process.php',
data: $.param({action: 'fetch', id: id}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (response) {
if (!response.success) {
alert("something went wronge");
return false;
} else {
$scope.formData = response.data;
$scope.student_id = response.data.id;
$scope.submit_button = 'Update';
$scope.$apply();
}
});
};

This is the way of the safe apply in the scope.
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
$scope.safeApply(function() {
alert('Now I'm wrapped for protection!');
});

Related

User is not defined Angular js

i have a problem when i click in the button it give me an error that user is not defined
i don't know what the problem
<input type="button" class="btn btn-danger" value="Active"
ng-click="Active(User)" />
this is my function in page Controller Asp MVC :
public string Active(AspNetUser User)
{
if (User == null) return "User Not Updated! Try Again";
var userToUpdate = db.AspNetUsers.Where(x => x.Id == User.Id).FirstOrDefault();
if (userToUpdate == null) return "User Not Found.";
if (userToUpdate.IsActive == true)
{
userToUpdate.IsActive = false;
}
else
{
if (userToUpdate.IsActive == false)
{
userToUpdate.IsActive = true;
}
db.SaveChanges();
return "User successfully Changed";
}
return "User already changed";
}
and this is my Script :
$scope.Active = function() {
$http({
method: "post",
url: "http://localhost:61484/AspNetUsers/Active",
datatype: "json",
data: JSON.stringify(User)
}).then(function(response) {
alert(response.data);
$scope.GetAllData();
})
};
You are not passing anything to the function $scope.Active. Pass the User:
$scope.Active = function(User) {...}
The datatype property is ignored by the AngularJS framework. Also it is not necessary to stringify JavaScript objects. The AngularJS framework does that automatically.
$scope.Active = function(user) {
$http({
method: "post",
url: "http://localhost:61484/AspNetUsers/Active",
̶d̶a̶t̶a̶t̶y̶p̶e̶:̶ ̶"̶j̶s̶o̶n̶"̶,̶
̶d̶a̶t̶a̶:̶ ̶J̶S̶O̶N̶.̶s̶t̶r̶i̶n̶g̶i̶f̶y̶(̶U̶s̶e̶r̶)̶
data: user
}).then(function(response) {
alert(response.data);
$scope.GetAllData();
})
};
For more information, see
AngularJS $http Service API Reference

Textbox binding not working when page has loaded AngularJS [duplicate]

This question already has answers here:
How to get promise result using AngularJS
(2 answers)
Closed 3 years ago.
I'm trying to set textbox value based on the result of promise values when page has loaded. The values on textbox set only if I click on it and then out of it (just like blur event).
Controller
(function() {
'use strict'
var newPurchasingCardController = function($scope, $rootScope, $filter, $window, $location, $timeout, requestService) {
$scope.actionTitle = "";
$scope.gin = "";
$scope.fullName = "";
$scope.workEmail = "";
$scope.msg = "";
var getCurrentUserData = function () {
var dfd = new $.Deferred();
var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
$.ajax({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: onSuccess,
error: onError,
cache: false
});
function onSuccess(data) {
dfd.resolve(data);
}
function onError(data, errorCode, errorMessage) {
dfd.reject(errorMessage);
}
return dfd.promise();
}
var _init = function () {
$scope.actionTitle = "New Card Request"
var promise = getCurrentUserData();
promise.then(function (data) {
$.each(data.d.UserProfileProperties.results,function(i,property){
if(property.Key === "EmployeeNumber")
{
$scope.gin = property.Value;
}
if(property.Key === "FirstName")
{
$scope.fullName = property.Value;
}
else if (property.Key === "LastName") {
$scope.fullName += " " + property.Value;
}
if(property.Key === "WorkEmail") {
$scope.workEmail = property.Value;
}
console.log(property.Key+":"+property.Value);
});
}, function(error) {
console.log("An error has occurred trying to get employee information." + error);
});
}
$scope.$on('$viewContentLoaded', function(event)
{
_init();
});
}
angular.module('myApp').controller('newPurchasingCardController', ['$scope', '$rootScope', '$filter', '$window', '$location', '$timeout', 'requestService', createnewPurchasingCardController]);
}());
And in the html view I just have
HTML
<input ng-model="gin" type="gin" class="form-control" id="gin" placeholder="GIN">
<input ng-model="fullName" type="name" class="form-control" id="name" placeholder="Name">
<input ng-model="workEmail" type="email" class="form-control" id="email" placeholder="Email">
I have tried with viewContentLoaded but not working, what would be a good approach to accomplish this? Thanks.
You are mixing angularjs with Jquery and that causes all the problems.
Use $http service for get request : https://docs.angularjs.org/api/ng/service/$http#get
var getCurrentUserData = function () {
var queryUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties";
$http({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
cache: false
})
.then(function(response) {
$scope.gin = response.data.EmployeeNumber;
// here set scope variables directly
})
.catch(function(response) {
console.error('error', response.status, response.data);
})
.finally(function() {
console.log("finally ");
});
}

How can i use array of objects from database as filter?

// filter with data from database not working
app.filter('position', function($http, dbOperations) {
console.log(dbOperations.getAccessPosition());
var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];
// get the object array from database with name and id
dbOperations.views("getPositions", "").then(function(res) {
positions = res; // this is the desired value: [{name:"cashier",id:1},{name:"operator",id:2}]
});
var poitionName = "";
return function(positionNum) {
positions.forEach(function(p) {
if (p.id == positionNum) {
poitionName = p.name;
return false;
}
});
return poitionName;
}
});
app.service('dbOperations', function($http) {
this.getAccessPosition = function() {
return $http({
method: "POST",
url: "/common/functions.php",
data: {
'process': "getAccessPosition",
'data': ""
}
}).then(function success(res) {
return res;
}, function myError(response) {
// console.log("Error");
});
}
});
When I console.log the positions, it prints the data that I need. but the filter is not working. maybe because the data is from database and it is waiting to respond. dbOperations is the in the service and I use $http.
Please help me with this. Thankyou.
In the service, just return the http request instead of unwrapping the promise.
app.service('dbOperations', function($http) {
this.getAccessPosition = function() {
return $http({
method: "POST",
url: "/common/functions.php",
data: {
'process': "getAccessPosition",
'data': ""
}
})
}
});
in the filter do the service call inside the callback function.
app.filter('position', function($http, dbOperations) {
console.log(dbOperations.getAccessPosition());
var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];
var poitionName = "";
return function(positionNum) {
dbOperations.views("getPositions", "").then(function(res) {
positions = res.data;
positions.forEach(function(p) {
if (p.id == positionNum) {
poitionName = p.name;
return false;
}
});
return poitionName;
});
}
});

Change $scope value after http request

I am trying to show different divs depending the response I get from an http request.
$scope.firstStep = true;
$scope.secondStep = false;
$scope.thirdStep = false;
$http({
method: 'GET',
url: '/api-web/ec/cadastro/recuperar-acesso',
data: {
filiacao: $scope.currentFiliacao,
cnpj: $scope.currentCNPJ
},
headers: {'Content-Type': 'application/json'}
}).then(function(res){
$scope.firstStep === false;
if (res.data.code === -1) {
$timeout( function (){
$scope.secondStep === true; //here is the bug, it dont change to true
console.log("second", $scope.secondStep);
}, 3000)
}
})
I tried several things, like $apply(), _defer, switch from === to =
... and I have no idea why its happening.
Any ideas ?
Doesn't this work?
$timeout( function (){
$scope.secondStep = true;
$scope.apply();
console.log("second", $scope.secondStep);
}, 3000)

Prevent $watchCollection to be triggered on init

I have "$scope.postits" array which I want to be persisted at every change. So, I put $scope.$watchCollection on this element to listen for changes and save data. The problem is that $watch is triggered 3 times on page load (my test array has 3 entries).
How to prevent that ? What's wrong with my code ?
view:
<div ng-controller="postitController as postit" class="container animate-bottom">
<h2>Post-it !</h2>
<div class="btn-container">
<button ng-click="addPostit()" id="add-new-note" class="btn btn-primary">Add postit</button>
</div>
<div class="post-it-container">
<div ng-repeat="postit in postits" class="postit">
<a ng-click="removePostit(postit)" class="delete-postit glyphicon glyphicon-remove"></a>
<textarea ng-model="postit.content" ></textarea>
</div>
<div ng-if="postits.length==0" class="no-postit well lead">Keep cool and have a beer there's no postit here !</div>
</div>
</div>
JS controller :
app.controller('postitController', function($scope, $http, $timeout) {
$scope.postitsLoaded = false;
var storage = {
endpoint: "localhost/backend/ws.php",
get: function() {
$http({
method: 'GET',
url: this.endpoint
}).then(function successCallback(response) {
$scope.postits = response.data;
$scope.postitsLoaded = true;
console.log("init done") ;
}, function errorCallback(response) {
console.log(response);
});
},
save: function () {
$http({
method: 'POST',
url: this.endpoint,
data: "postits="+ angular.toJson($scope.postits),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log(response);
alert("error");
});
}
}
$scope.$watchCollection("postits", function (newValue, oldValue) {
if(newValue === oldValue || !$scope.postitsLoaded){
console.log("return") ;
return;
}
console.log("watch triggered") ;
storage.save();
});
$scope.addPostit = function() {
$scope.postits.push({id:100,content:"foobar"});
storage.save();
};
$scope.removePostit = function(postit) {
$scope.postits.splice($scope.postits.indexOf(postit), 1) ;
storage.save();
};
storage.get();
});
This is finally working with $watch and the third parameter set to true :
$scope.$watch("postits", function (newValue, oldValue) {
//this prevent $watch to be triggered on init
if(newValue === oldValue || oldValue === undefined ){
console.log("return") ;
return;
}
console.log("watch triggered") ;
console.log(oldValue);
console.log(newValue);
storage.save();
},true);
with that solution there is not need to use any flag.

Categories

Resources