My $scope value not updating - angularjs

updated object is not getting without using location.reload
Hi i will get list of objects from API where i have to update one value,After updating that value in modal popup i am not able to get new updated value without using location.reload. Is there any other solution for this.i am using two different controllers.
Will get list of objects from this
$scope.groups=response.data
will ng-repeat this groups where i will have edit button for every line,Once i click edit button popup will open
$scope.editGroup = function(u) {
$scope.groupName=u.groupName;
$scope.groupId=u.groupId;
ModalService.showModal({
templateUrl: 'app/components/modal/editGroupDetails.html',
controller: "ModalController",
scope: $scope
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {
$scope.message = "You said " + result;
});
});
};
Next once i edit the GroupName i will click submit
$scope.updateGroupName=function(){
var data={
"groupId": $scope.groupId,
"groupName": $scope.groupName
}
url=globalUrlConfig.globalAdminApi+globalUrlConfig.updateGroup+$scope.schoolId;
$http({
method: 'PUT',
url: url,
data: data,
}).success(function(response) {
console.log(response)
if(response._statusCode==200){
alert(response.data);
location.reload();
}
else{
alert("not updated")
}
})
}
Without using location.reload i am not able display updated data

Use $rootscope like this
Add this $rootScope.$emit("refreshData", {});
instead of Location.reload();
And then add this in your main controller for load data without refresh
var RefreshValue = $rootScope.$on("refreshData", function () {
GetValueMethod(); // call your method (List of object) for get data without reload form
});
$scope.$on('$destroy', RefreshValue);
Don't forget to inject $rootScope.

Related

angularjs templates not hiding div from route

It's two page user registeration process depending on the role the second page could be different but the first page will always remain the same. what I want I that user can go forward and backwards on both screens with persistent data. I trying a static page at start and then hide it and add the second template from route.
This is my angular app controller.
app.controller('addlandlordController' , function($scope , $http , $route ,API_URL , $routeParams , uploadService ){
$scope.API_URL = API_URL;
$scope.landVisible = true;
$scope.IsVisible = true;
if( $routeParams.test)
{
scope.$apply(function () {
$scope.IsVisible = false;
});
alert( $routeParams.test);
}
$scope.adduser = function($route){
var data = $.param({
fName: $scope.firstName,
lName: $scope.lastName,
role: 'landlord',
email: $scope.email,
linkId: $scope.linkId,
password: $scope.password,
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post(API_URL + 'user' , data , config)
.then(
function(response){
//$scope.IsVisible = false;
//alert('success');
},
function(response){
// failure callback
alert('fail');
}
);
}
});
I have a div in html like this,.
<div id="content" class="container1" ng-controller='addlandlordController' >
<div ng-show = "IsVisible">
And following is my route in config,.
app.config(function($routeProvider){
$routeProvider.when('/landlord' , {
templateUrl : 'template/addlandlord.html',
controller : 'addlandlordController',
resolve: {
test: function ($route) { $route.current.params.test = true; }
}
})
});
What I want is that when the user click on the following button.
Create an Account</button>
On click that button #/landlord will be added to the url and the route config code will run and add the other template in ng-view which is happening. Now next step is to hide the old div above in such a way that when user go back one sten only the previous code should show and when user goes again into the next screen only the next template should be visible and mean while data should remain same for the both views.
Issues I am facing is
Css is for template view is missing although the css files are already in the commen header. But appears when a place css in the style within template.
if I hide the first div in the response of adduser then if user go back it still hidden. it doesn't appears unless I refresh the page.
But if went to hide it through route config the value turn false but div never hides.
Please check this
scope.$apply(function () {
$scope.IsVisible = false;
});
You are using $apply on scope, but not in $scope.
And $applyAsync is preferable method to trigger digest without risking of error "$digest already in progress"
$applyAsync example:
$element.on('click', ()=>{
$scope.model.testValue = 'I have been updated not from angular circle';
$scope.$applyAsync();
});
Link to the docs
Nice article to read

Changing states but controller is not being called in angular js

I have a webpage which displays the user profile information from the database which is working fine, and another one in which user edits his/her information, which is edited in the database, which is also working. But after I change the data in the second webpage, I have changed the state to the first page using $state.go, which also seems to be working, but the newly updated data is not showing in this first page, the controller is not being called I think.
This is my controller of webpage which shows the userprofile :
.controller('myProfileCtrl', function (..parameters..) {
$scope.id = window.localStorage.getItem("profileId");
$scope.$root.loading = true;
$http.get('my link...')
.success(function (data) {
$scope.first_name = data[0].first_name;
$scope.middle_name = data[0].middle_name;
})
This is the controller of my second page which updates the user information :
.controller('editPersonalCtrl', function (..parameters..) {
$scope.saveChanges = function (user) {
$http.post('my link..', {
changeFirstName : new_first_name,
changeMiddleName : new_middle_name,
})
.success(function (data) {
$state.go('profile');//Go to the first webpage
$ionicHistory.nextViewOptions({
disableBack: true,
historyRoot: true
});
})
.error(function (data) {
alert("ERROR" + data);
});
}
The state changes but the newly updated data is not shown, I mean the controller of the first webpage is not working, otherwise it would have fetched the new data from the database and displayed it. The old data is showing.
replace
$state.go('profile');
with
$state.go('profile', {}, { reload: true });
It will force the to transit and than also it's not working you can do like
$state.go('profile', {}, {reload: true,notify: true});
This will force and also will broadcast $stateChangeStart and $stateChangeSuccess events. Here is the ref

$http.get method not working on ng-submit

I want $http.get method to work when a form is submitted.
Here is my code. The object $scope.questions is being set when the method is called but the data doesn't show up in the div. Moreover, when the $http.get method is outside the signIn() function it works just fine.
$scope.signIn = function(data) {
$location.path('/profile');
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
});
};
<div>
User Profile
<br/>Question Posted
<br/>
<input ng-model="query.title" id="value" type="text" placeholder="Search by Title..." ">
<div>
<ul>
<li ng-repeat="question in questions | filter: query ">
{{question.title}}
</li>
</ul>
</div>
<br/>
</div>
You need to move your $location.path('/profile') inside your http request. Remember that a http request is async call. You should redirect after getting the data not before.
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
$location.path('/profile');
});
};
If you're redirecting to another route with a completely separate scope you will lose any scope you're setting in the success handling.
From what I'm reading you're clicking a button to do an action. After that action you're redirecting to another page with a separate controller and trying to persist the data.
Unfortunately, Angular hasn't figured out a great way to do this. The easiest way to persist data through controllers and scope is to create a service that will store it in one controller and grab it in another controller.
For instance:
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$location.path('/profile');
storageService.store("question", questiondata)
});
};
Your new factory to persist data through:
angular.module('moduleName').factory('storageService', [
function () {
return {
store: function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get: function(key) {
return JSON.parse(localStorage.getItem(key));
},
remove: function(key) {
localStorage.removeItem(key);
}
}
}
]);
Other controller to access data:
$scope.question = storageService.get("question");
// remove localstorage after you've grabbed it in the new controller
storageService.remove("question");
An alternative to doing the somewhat 'hacky' way of using localStorage to persist data through controllers is to use ui-router and have a resolve on the route you're redirecting to.
For instance:
$scope.signIn = function(data) {
$state.go('profile');
};
In your route file:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(res) {
return res.data;
});
}]
}
}
In your profile controller:
Inject your 'questions' resolve into your controller and assign `$scope.question = questions;
This will make the HTTP call as soon as you click the route, return the data if successful, then render the page. It will NOT render the page if the resolve does not return success. This will ensure your data will be loaded before you load the page that depends on that data.
I would highly recommend using services to hold your HTTP calls for specific parts of your application. If you have a GET questions, POST question, PUT question. I would create a questionService and make all my HTTP methods there so you don't have to clutter your routes. You would only have to call:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
return questionService.getQuestions(id).then(function(res) {
return res.data;
})
}]
}
}

DOM loading before the promise defer completes

I have a model that I am using to hold my data in angular:
var FuelProcessingModel = function (carrierService) {
this.myArray = [];
};
That model has an array of MyObjects that I get from the DB:
var MyObject = function () {
//stuff
}
I update this using a REST call:
$scope.add = function () {
var myObject = new MyObject();
fuelProcessingService.add(myObject).then(function(result) {
$scope.model.MyObjects.push(result.data);
});
};
Here you can see I want to push the result to the array so that it is added on the screen. But the problem is the DOM loads before that happens.
service to hit the Server:
this.add = function (myObject) {
var deferred = $q.defer();
$http({
method: "POST",
url: "theServer",
data: myObject,
}).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
The REST service adds to the Database and then returns the updated object
I thought that $q.defer() would cause the DOM to wait to load until the result is returned so that the newly added item shows up.
What am I missing?
UPDATE
I tried doing this but I still have the same problem. The push call is not being called before the DOM loads the page, so the user never sees the added item.
this.add = function (myObject) {
return $http({
method: "POST",
url: "theServer",
data: myObject,
}).success(function (data) {
return data;
});
Html that creates and uses the object
<div ng-repeat="myObject in model.MyObjects" style="margin-bottom: 2%">
//A table of myObjectData
<button class="btn btn-success" ng-click="add()">Add My Object</button>
</div>
Here is what happens in Angular.
Initial html is rendered (also called template html).
Angular boostraps, and then does the necessary binding and the view is updated.
Angular watches for changes and if there is a change in data, view is updated automatically.
When you bind the array to the view the, it renders what is available. When you add some new element to the array later the view should automatically update. You do not need to bother with creating your own promise just do
return $http...

angular $resource removes a property when object changes

I've created a Service that returns a $resource
module.registerFactory('Website', function ($resource, $cacheFactory) {
var cache = $cacheFactory('websites');
var pagedCache = $cacheFactory('websites_paged');
return $resource('/api/websites/:id', {id: '#id'}, {
query: {method: 'GET', isArray: false, cache: pagedCache},
get: {method: 'GET', cache: cache}
});
});
In an edit state I receive all details by calling
$scope.website = Website.get({'id': $stateParams.id});
The $scope.website promise contains my data as expected. (Below a shortened JSON result from server)
{"id":25,"name":"blabla","url":"http://here.com","description":"blabla",
"tags":[
{"id":6,"name":"..."},
{"id":7,"name":"..."}
{"id":10,"name":"..."}
],
"objectives":[
{"id":3206,"code":"WIS AD3.c","name":"[ommitted objective 3206]","parent_id":3203},
{"id":3209,"code":"WIS AD4.b","name":"[ommitted objective 3209]","parent_id":3207}
]}
My problem is with the objectives property.
In my EditCtrl I open a modal and send the objectives as selected items to the modal. That works perfect.
$scope.selectObjectives = function () {
var modalInstance = $modal.open({
templateUrl: 'app/modules/objectives/templates/select-objectives.html',
controller: 'SelectObjectivesModalCtrl',
size: 'lg',
resolve: {
selectedItems: function () {
return $scope.website.objectives;
}
}
});
modalInstance.result.then(function (selectedItems) {
$scope.website.objectives = selectedItems;
console.log($scope.website);
});
}
When closing the modal the newly selectedItems are injected back into $scope.website.objectives. (cfr. modalInstance.result.then() ... )
The console logs perfectly all properties - including the objectives.
Now comes the weird part:
As soon as I try to access $scope.website in another function (ie update)
The objectives property is removed from $scope.website.
This is my update method:
$scope.updateWebsite = function () {
console.log($scope.website);
$scope.website.$save(function () {
$cacheFactory.get('websites').remove('/api/websites/' + $scope.website.id);
$cacheFactory.get('websites_paged').removeAll();
$state.go('app.websites');
});
};
The console logs all properties in $scope.website - except for the objectives. This is completely removed.
I hope I made myself clear enough.
Thanks for taking some time to help me pointing to the right direction.
My bad.
My response didn't return the entire object as should be in a RESTful POST.

Resources