Data can not be synchronized using angularjs - angularjs

I store a data in a factory like this:
module.factory('AddedStockListData', function(){
var list= [];
var size = 0;
return{
getList: function(){
return list;
},
setList: function(data){
list = data;
},
getSize:function(){
return size;
},
setSize:function(){
size++;
},
setDelSize:function(){
size--;
}
}
});
And in my controller the code as follows:
$scope.stocksSearchList = AddedStockListData.getList();
$scope.load = function($done){
$timeout(function() {
document.getElementById("showTipsToDropDown").style.display = "none";
$scope.stocksSearchList = AddedStockListData.getList();
$done();
}, 500);
}
My html like this:
<ons-page ng-controller="createPortStockController">
<ons-pull-hook ng-action="load($done)" var="loader" id="pullDown">
<span ng-switch="loader.getCurrentState()">
<span ng-switch-when="initial"><ons-icon size="35px" icon="ion-arrow-down-a"></ons-icon> Pull down to refresh</span>
<span ng-switch-when="preaction"><ons-icon size="35px" icon="ion-arrow-up-a"></ons-icon> Release to refresh</span>
<span ng-switch-when="action"><ons-icon size="35px" spin="true" icon="ion-load-d"></ons-icon> Loading data...</span>
</span>
</ons-pull-hook>
<div>
<ons-toolbar class="DCF" fixed-style>
<div class="left">
<ons-back-button style="color:white;"></ons-back-button>
</div>
<div class="center" style="font-size:22px;" >Create Portfolio</div>
<div ng-click="create()"class="right" style="font-size:18px;color:white;margin-top:10px;padding-right:10px;" >Create</div>
</ons-toolbar>
<div class="addStockButton" ng-click = "myNavigator.pushPage('portStockSearchList.html', { animation : 'slide'})">
<i class="fa fa-plus" ></i>Add Stock
<p id="showTipsToDropDown"style="margin:0px;font-size:12px;text-align:center;color:#adadad;">After your first time add stocks, please drop down to refresh</p>
</div>
<div class="stockSearchList">
<div ng-repeat="stockSearch in stocksSearchList">
<div class="stockSearchOne">
<div class="stockSearchOneComp">{{stockSearch.company}}</div>
<div class="stockSearchOneInfo">Symbol: {{stockSearch.symbol}} | Exchange:{{stockSearch.exchange}} </div>
</div>
</div>
</div>
</div>
Actually, I change the factory data in next page,I want to make this page change the display while the factory data is changed.
But the result is , at the first time I change the data in the next page and back to this page, the data will not display, and I will refresh this page by use the ons-pull-hook> and then if I go to the next page to change the data, when I back to here, data will be synchronized display .
So the result is at the first time , I have to refresh the page to get the data, but after the first time, I don't need to do this
Anybody can help me to solve this problem?

Try using $scope.$apply() after the data have been fetched, it should update the content without any need to refresh the page. You can learn more about $scope.$apply() here.

Related

Angularjs delay append new data and display old data 1s

It delays append new data and display old data 1s when I click: https://youtu.be/KeqRdGueekg
In controller:
myApp.controller('Notebook', function($scope, $http){
//Display Note click NoteBook
$scope.xl_note = function(id){
$http.get("/thunder_note/notebooks/show_note?id=" + id)
.then(function(response) {
$scope.dataNote = response.data;
});
};
});
In view:
<div class="modal-body">
<div class="list_body list_body_note_of_notebook">
<div class="list_content show_noteaas" ng-repeat="data in dataNote.Note">
<a href="/thunder_note/notes/note_detail/{{data.id}}" style="text-decoration: none;">
<p class="title">{{data.title}}</p>
</a>
</div>
</div>
</div>
when you call /thunder_note/notes/note_detail/
you do 2 things calling api and redirecting page
the page ridects immidiate so there is allready old data
but api response takes some time for getting response
so clear $scope.dataNote =""; before your calling api

How to add text box runtime and insert its value to db in angularjs

I want to create Curd app using AngularJS & MVC.
In that I am able to add, update and delete particular data from grid, but there is one task where I am getting stuck.
Here what I need to do is, I should be able to add multiple run time text box on that insert page to take any no of input from user, so I don't know how to do it and how to add those run time added text box values in DB.
It would be much appreciated if you help me on this.
Try this,
Here is the working fiddle
<div ng-controller="MyCtrl">
<div class="row" ng-repeat="(key,val) in data">
<div class="col-md-12">
<input type="text" ng-model="val.text">
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary" ng-click="addTextbox()">
Add Textbox
</button>
</div>
<div class="col-md-12">
<button class="btn btn-success" ng-click="sendDataToServer()">
Send Data
</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
Result = {{data}}
</div>
</div>
</div>
Controller's code
var myApp = angular.module('myApp',[]);
function MyCtrl($scope,$http) {
$scope.data = [];
$scope.addTextbox = function(){
$scope.data.push({'text':''});
}
$scope.sendDataToServer = function(){
console.log(JSON.stringify($scope.data));
$http({
url: 'your_server_url',
method: "POST",
data: JSON.stringify($scope.data),
headers: {
'Content-Type': undefined
}
}).then(function(res) {
// do stuff on success
}, function(errorMsg) {
console.log(errorMsg);
// showing error
});
}
}
Here you will get all textbox's data into $scope.data, Now you can send this data by clicking Send Data button.
Provide the url where you want to submit this data.
Comment if you have any issue.

post.length stays 0 due to loop - AngularJS

I'm trying to add pagination but I can't seem to figure out this last part.
Everything is setup, though my pagination isn't recording the amount of posts that are linked with the user.
Seeing that I'm doing a forEach and if loop and pushing the retrieved items into a empty collection, my 'posts.length' is returning 0.
Hence the pagination only showing page 1/1 and not 1/2 (for example).
Here is my full code:
profileCtrl.js
Here is the $http.get - I'm trying to get all the posts that the logged in user made doing this loop:
app.controller('profileCtrl', function($scope, auth, $http, $log) {
$scope.auth = auth;
$scope.date = auth.profile.created_at;
$scope.pageSize = 5;
$scope.posts= [];
$http.get('URL')
.then(function(result) {
angular.forEach(result.data, function(data, key) {
if(data.userId === auth.profile.user_id) {
$scope.posts.push(data);
}
});
});
});
profile.html
As you can see, I'm trying to get the length of post in posts using total-items="posts.length":
<div class="col-md-8 no-padding-right">
<div class="panel panel-primary">
<div class="list-group-item active text-center">
<h4 class="no-margin-top no-margin-bottom">Recent Activity</h4>
</div>
<a href="#" class="list-group-item" ng-repeat="post in posts| startFrom: (currentPage - 1) * pageSize | limitTo: pageSize | orderBy :'created_at':true">
<div class="row">
<div class="col-md-4">
<div class="thumbnail no-border no-margin-bottom">
<img src="https://placehold.it/150x150" alt="bird" width="150" height="150"/>
</div>
</div>
<div class="col-md-8">
<h4 class="no-margin-top no-margin-bottom"><strong>{{post.birdname}}</strong></
</div>
</div>
</a>
<uib-pagination total-items="posts.length" ng-model="currentPage" max-size="pageSize" boundary-link-numbers="true"></uib-pagination>
</div>
</div>
app.js
I also added a filter in app.js:
app.filter('startFrom', function() {
return function(data, start) {
return data.slice(start);
}
});
When I console.log(posts.length); I keep getting 0 and I'm guessing it's because of the $scope.posts = []; declared on top (profileCtrl.js).
Edit:
After doing a bit of debugging with console.log, I do get the value given when doing this:
$http.get('url')
.then(function(result) {
angular.forEach(result.data, function(data, key) {
if(data.userId === auth.profile.user_id) {
$scope.posts.push(data);
}
});
console.log($scope.posts.length);
});
How should I fix this?
If you're waiting for data to be returned before loading the collection (with pagination) either add a ng-if="posts.length" to the container, or initialise $scope.posts as being null and add ng-if="posts" if you want the list to show when the API returns 0 results. This will prevent Bootstrap's pagination directive being parsed until the data it needs is available.
Edit: After debugging, the following plunkr contains a working implementation: http://plnkr.co/edit/VQjNVK6gRKsCqxVb54nR?p=preview

Update facebook page list in to a drop down list

I am working on an angular app which integrates with facebook. I have given the code below,
$scope.getCompanyPages = function () {
fb.login(function (response) {
fb.api('/me/accounts', function (apiresponse) {
if (typeof apiresponse !== 'undefined' && typeof apiresponse.data !== 'undefined') {
$scope.facebookPages = apiresponse.data;
$scope.facebookPages.push({ id: "", name: 'Please select a page' });
$scope.selectedItem = $scope.facebookPages[2];
console.log($scope.facebookPages);
}
});
}, { scope: 'manage_pages' });
};
HTML
<div class="row">
<div class="col-xs-12 col-sm-6 center">
<a href="#" ng-click="shareToMyWall()">
<div class="primary-task">
<i class="fa fa-user fa-3x">
</i>
<h2 class="heading-text fa-bold">Personal Wall</h2>
</div>
</a>
</div>
<div class="col-xs-12 col-sm-6 center">
<a href="#" ng-click="getCompanyPages()">
<div class="primary-task">
<i class="fa fa-building fa-3x">
</i>
<h2 class="heading-text fa-bold">Company Wall</h2>
</div>
</a>
<select ng-if="facebookPages.length > 0" ng-change="shareToFacebookPage(selectedItem.id)" ng-model="selectedItem" ng-options="item.name for item in facebookPages track by item.id"></select>
</div>
</div>
The above method is called in hyperlink click (ng-click) event and the when the response comes back the drop down should update with data. The data does come back but it doesn't update straight away, rather I have to do another click anywhere in the page to update drop down list.
The data in the model is updated when you do the first ng-click. However, AngualrJS probably does not do check so the view still shows the old data. You can force a $digest() check and tell AngualrJS to compare old data and new data and update it if there is any difference. You can use $timeout, $evalAsync, or $apply to trigger $digest() which will update the data immediately.
For example:
$timeout(function () {
$scope.getCompanyPages = function () {...}
//or
$scope.facebookPages = apiresponse.data;
})
Edit: according to Angular JS best coding practice
Always wrap 3rd party API call-backs in to $apply to notify AngularJS
regarding out of environment changes.

AngularJs how to reload a template page after selecting a charater

I am using http.get and i need to reload a template after selecting a character so that my template gives the answer according to what I selected
The code of the template
<div class="container-fluid" ng-controller="CriterioCtrl">
<div id="result"></div>
<div>
Selected Items:
<div ng-repeat="id in selection">
{{id}}
</div>
</div>
<div ng-repeat-start="crit in data" class="row">
<h2 align="center">{{crit.name}}</h2>
<div ng-repeat="caracter in crit.characters" class="col-md-4">
<div type="checkbox" value="{{caracter.id}}" ng-checked="selection.indexOf(caracter.id) > -1" ng-click="clickSelection(caracter.id)">
<a href="#crit" class="thumbnail" ng-click="clickCriterios(caracter.id)">
<h4 align="center">{{caracter.name}}</h4>
<img ng-src="http://skaphandrus.com/{{caracter.image_url}}"/>
</a>
</div>
</div>
</div>
<div ng-repeat-end>
</div>
<!--<button class="btn" ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p> codigo de um botao -->
</div>
This code is for the selection
$scope.selection=[];
$scope.clickSelection = function clickSelection(caracterId) {
var idx = $scope.selection.indexOf(caracterId);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(caracterId);
}
var selectedId = $scope.selection;
console.log(selectedId);
// Check browser support
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("idSelect", selectedId);
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("idSelect");
}
};
This code is the http part in another controller
MyApp.controller('EspeciesCtrl', function ($scope, $http) {
$http({
url: 'someurl',
method: "post",
params: {module_id: localStorage.getItem("idMod"),"characters[]": [localStorage.getItem("idSelect")]}
})
.then(function(res){
$scope.data = res.data;
});
});
This is the code of the template that have to change after the selection
<div class="container-fluid" ng-controller="EspeciesCtrl">
<div class="row">
<div ng-repeat="esp in data" class="col-md-6">
<a href="#infEsp" class="thumbnail" ng-click="clickEspecie(esp.id)">
<h4 align="center">{{esp.name}}</h4>
<img ng-src="{{esp.image_src}}"/>
</a>
</div>
</div>
</div>
How can i do that?
edit 1
If I've correctly understood, you may need to use ng-show (https://docs.angularjs.org/api/ng/directive/ngShow) whose boolean value checks if the user selected anything and show the extra bit of code you need, instead of trying to have another http request.
Also, it seems like you are using $scope.data for both the esp and the crit, so you will end up with the errors.
You probably don't need to reload the template.
You may want to use the data in $scope.data inside the template in order to let Angular manage the update on the view. As soon as the $scope.data changes, the rendered HTML changes too.
I can't comment but it would be helpful if you could share the template you are using and be more specific in your request :)

Resources