Angularjs scope data inside the function - angularjs

I am trying to display the data to my view but $scope.plan outputs {}. I am thinking that it would output the fetched data from the initGetEdit function, console.log() inside the $http.post outputs expected data.
controller.js
var id = $stateParams.id;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
$http.post("someUrl", data).then(function(res){
$scope.plan = res.data;
console.log($scope.plan); //----> logs expected data
})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
In my view I have something like this.
view
<input ng-model="plan.something" type="text" />
UPDATE
First thank you for those answers provided and the comments, appreciated it. It gives me an insight. I solved my issue by removing the initGetEdit function and staying with just the http.post.

Try keeping the second console in watch.
$scope.$watch('plan',function(){
console.log($scope.plan);
});

At first, you declare a variable $scope.plan = {} after that in http call of your $scope.initGetEdit function its empty object after the function http is an async call your object may be filled based on the response. until that it will be an empty object.
#Ujjwala Bollam mention in answer to print it in the console.
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope,$http){
//var id = $stateParams.id;
var id=1;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
//$http.post("http://someurl", data).then(function(res){
$scope.plan ={id:1,something:"hai this is response data"};
console.log($scope.plan); //----> logs expected data
//})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<input ng-model="plan.something" type="text" />
</div>

Related

Fetch data from database in angularjs to form

In front page there are two options:
1.create new
2.edit
1.it goes to index.html
2.it should be goes to index html with data(data should be load from database)
//get data from database
$scope.getItem = function(id) {
var auth = btoa("root:root");
$scope.form["#class"] = "ProjectDetails";
$http.defaults.headers.common.Authorization = 'Basic ' + auth;
$http.get("http://azuspeedcp01:2480/document/InternalRPA/"+id+"/*:-1", {
})
.then(function(response) {
console.log(response);
$scope.form=response.data;
});
}
here i retrieve data from db is fine.its response.data
again assign to $scope.form which is the object i passed from form to submit data.
//index.html(partial)
<input type="text" id="clientName" ng-model="form.ClientName">
<input type="text" id="initiate" ng-model="form.City">
<select id="Geo" ng-model="form.Geo">
<option value="North America">North America</option>
</select>
How to route to index.html with data. I don't have idea.please help me.
it goes to index.html
it should be goes to index html with data(data should be load from database)
So you want always staying in the same screen, then why you want to redirect(refresh) on the same screen? You can use the same scope object anywhere in the same screen(index.html),
it should be goes to index html with data(data should be load from database)
If you want to redirect with data. then Just use location.$path("routename") to redirect the screen and maintain the values by using $localStorage
I found the answer that I can use angular service to route from one service to another.Thanks all to help me
app.service('srvShareData', function($window) {
var KEY = 'App.SelectedValue';
var addData = function(newObj) {
alert("2"+newObj);
$window.sessionStorage.setItem(KEY,JSON.stringify(newObj));
};
var getData = function(){
var mydata = $window.sessionStorage.getItem(KEY);
return mydata;
};
return {
addData: addData,
getData: getData
};
})

After make ajax-post request the html elements are not refresh in angular

I have a issue.i make ajax-post request then it execute properly then i get the response.After process the response i need again make ajax-get then those data i set to a variables in the scope.the data are successfully assign in to variable but html elements are not refresh.this is the sample code.
this is html part
<div ng-controller="AppManagerCtrl" >
<md-list-item ng-repeat="app in apps">
<div>
<div flex="20" layout-padding>
<p>{{app.appId}}</p>
</div>
<div flex="20" layout-padding>
<p>{{app.appName}}</p>
</div>
</md-list-item>
</div>
this the angular service
app.service('AppManagerService',function($http){
this.loadApps = function(){
var request = $http.get('apps');
return request.then(handleSuccess,handleError);
};
this.submitApp = function(){
var request = $http.post('apps',
$('#newAppDetail').serialize(),
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
);
return request;
};
function handleError(responce){
console.log(responce);
}
function handleSuccess( response ) {
return response.data.value;
}
});
this the angular controller
app.controller('AppManagerCtrl', function($scope,$mdDialog,$mdMedia,AppManagerService) {
function loadApps(){
AppManagerService.loadApps().then(function(apps){
$scope.apps = apps;
console.log($scope.apps);
}
);
}
loadApps();
$scope.submitNewApp = function(){
AppManagerService.submitApp().then(function(responce){
var data = responce.data;
if(data.status == 1){
loadApps();
}
});
};
});
all these are in the html body.from the begin html part then angular service and finally controller.
The result of an ajax call isn't monitored by Angular, which is why your scope isn't updated (it will be on the digest though).
To solve this, you must manually call $scope.apply().
However, if another digest is already in progress, it will throw an error. So it's safer to use the $timeout utility:
function loadApps(){
AppManagerService.loadApps().then(function(apps){
$timeout(function() {
// update your scope variables here. The refresh will occur automatically.
$scope.apps = apps;
console.log($scope.apps);
});
});
}

how to get data by using ID in angular js?

I am trying to use angular-resource.js file in my demo .I am retrieving
data from json file using $resource and display my data using ng-repeat .But Each item I added one button (info text button).I need to get it infomation using $resource property.I am sending ID on click function .but when I am using $resource property it gives error to me
$scope.getIn=function(id){
// alert(id)
$scope.oneUser = Entry.get({user: id});
console.log($scope.oneUser)
}
here is my code
http://plnkr.co/edit/lB11oQkQjbILK36u8V25?p=preview
If i understand correctly what you are trying to achieve this should solve it:
angular.module('app',['ngResource']).controller('a',function($scope, GetData){
// read data from factory and store it in $scope.posts
GetData.then(
function successCallback(data) {
$scope.posts = data.data;
},
function errorCallback(response) {
console.log(response); // handle any errors
});
// buttonclick to return the values from the selected id
$scope.getIn = function(id){
angular.forEach($scope.posts, function(value) {
if(value.id === id)
{
$scope.selectedValue = value;
}
})
};
console.log($scope.posts)
})
.factory('GetData', function($http){ // use http to read the json
return $http.get('data.json');
});
And the html:
<body ng-app='app' ng-controller='a'>
<div ng-repeat='p in posts'>
<span>{{p.name}}</span>
<button ng-click=getIn(p.id)>info</button>
</div>
{{selectedValue}}
</body>

How to wait for response in angularjs

What I am doing is putting the filter on table (contains records). When I type into search box (used http get method), table data get updated as per search box. But when I type very fast, then I see in console 500 Internal Server error.
The main problem is before comming previous response I am firing the next request.
There is no problem in result. Just console shows every http request. And in case of fast typing in search box it gets red.
What is the solution for it?
you could trottle your search input :
var app = angular.module('app', []);
app.controller('TableController', function($scope, $http, $timeout) {
$http.get('yourTableData.json').then(function(result){
$scope.rows = result.data;
});
$scope.filterText = '';
var temp = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout){
$timeout.cancel(filterTextTimeout);
}
temp = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = temp;
$http.get($scope.filterText).then(function(result){
$scope.rows = result;
}
}, 250);
})
});
<input id="searchInput" type="search" placeholder="search field" ng-model="searchText" />
<div class="record" ng-repeat="row in rows | filter:filterText">
<span>{{row.content}}</span>
</div>

Value of variable becomes undefined after calling data service

I have a angular js controller 'TakeSurveyController' which calls a data service 'takeSurveyDataService'. The controller has a variable empId which I am accessing successfully using the 'this' keyword. However, the value of this variable becomes undefined soon after I make a call to the data service.
(function(){
dataUrls = {
employeeUrl : '/SurveyPortal/Company/Employees/'
}
angular.module('takeSurvey',[])
.service('takeSurveyDataService',function($http,$log){
this.checkEmployee = function(employeeId){
var url = dataUrls.employeeUrl + employeeId;
return $http.get(url);
};
})
.controller('TakeSurveyController',function($http,takeSurveyDataService,$location){
this.empId = '';
this.checkEmployee = function(){
takeSurveyDataService.checkEmployee(this.empId).then(this.attemptSurvey);//empId has value here. Call successful to data service
};
this.attemptSurvey = function(employeeResponse) {
if(employeeResponse.data=="true"){
$location.path('/attemptSurvey/'+this.empId); //empId variable undefined here, unable to access value that was available above
}
else{
this.empId = '';
alert("This empId has not been registered. Please register before taking survey!");
}
};
})
})();
Following is the html code.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div align="center" style="margin-top:50px">
<form name="checkEmployee" ng-controller="TakeSurveyController as takeSurveyController" ng-submit="takeSurveyController.checkEmployee()" >
<input type="text" ng-model="takeSurveyController.empId" placeholder="Employee ID" /><br>
<input type="submit" class="btn btn-large btn-success" value="Move to survey" />
</form>
</div>
</body>
</html>
You must be very carefull using this inside functions since 'this' words get different meaning each time depending on context. I believe during promise callback 'this' get's different meaning and it is loosing connection with TakeSurveyController. Please try to assign 'this' to 'self' variable which is always good practice in angular and js:
(function(){
dataUrls = {
employeeUrl : '/SurveyPortal/Company/Employees/'
}
angular.module('takeSurvey',[])
.service('takeSurveyDataService',function($http,$log){
var self = this;
self.checkEmployee = function(employeeId){
var url = dataUrls.employeeUrl + employeeId;
return $http.get(url);
};
})
.controller('TakeSurveyController',function($http,takeSurveyDataService,$location){
var self = this;
self.empId = '';
self.checkEmployee = function(){
takeSurveyDataService.checkEmployee(self.empId).then(self.attemptSurvey);//empId has value here. Call successful to data service
};
self.attemptSurvey = function(employeeResponse) {
if(employeeResponse.data=="true"){
$location.path('/attemptSurvey/'+self.empId); //empId variable undefined here, unable to access value that was available above
}
else{
self.empId = '';
alert("This empId has not been registered. Please register before taking survey!");
}
};
})
})();

Resources