ng-include template variable not changing on $scope.$watch (no button trigger)? - angularjs

I have a controller 'AController' that has a template variable, $scope.tpl.partialtemplate1 = 'initialcontactlist.html'.
'AController' basically is in charge of an entire page, 'mainpage.html', where we have
<div ng-include="tpl.partialtemplate1"></div>
On 'mainpage.html', there is a form to add contacts. This form is not part of 'partialtemplate1''s views.
Upon submitting the form, I want the HTML view for 'partialtemplate1' to be reset to what it was on initial page load, because it will then reload the latest list of contacts.
I have tried things like incrementing a variable after each new contact is successfully added, and then having that variable watched and the partialtemplate variable changed.
for example, in 'AController':
$scope.tpl = {};
$scope.contactcount = 0;
$scope.contactsignupdata = new Contact();
$scope.tpl.partialtemplate1 = 'initialcontactlist.html';
$scope.successmessage = null;
$scope.addcontact = function() {
$scope.contactsignupdata.$save();
$scope.successmessage = 'Saved!';
$scope.contactsignupdata = new Contact();
$scope.contactcount = $scope.contactcount + 1;
};
$scope.$watch('contactcount', function(newValue, oldValue) {
$scope.$apply(function() {
$scope.tpl.partialtemplate1 = null;
$scope.tpl.partialtemplate1 = 'initialcontactlist.html';
});
/*$scope.partialtemplate1 = 'projecttasklists.html';*/
});
Why isn't the partialtemplate variable getting changed? Yes, the contact gets successfully saved each time - I took care of that with the Rails factory...

Your code sets partialtemplate1 to null, then straight back to 'initialcontactlist.html'. As far as Angular is concerned, nothing is changed. True bindings are not supported meaning that just because you changed partialtemplate1, doesn't mean it immediately happens or triggers any special events. For this specific scenario, you would have to set partialtemplate1 to null, set a timer, then trigger the change back to 'initialcontactlist.html'
I do not recommend this by the way
$scope.$watch('contactcount', function(newValue, oldValue) {
$scope.$apply(function() {
$scope.tpl.partialtemplate1 = null;
$timeout(function() {
$scope.tpl.partialtemplate1 = 'initialcontactlist.html';
}, 1000);
});
});
I highly recommend
Creating an API for Contacts that you can query. That way when a Contact is created, updated, or removed you can handle it yourself in a couple ways:
You can requery the data source each time something changes
If the API returns data related to the change, you don't need to requery
You should look into creating Angular Services and/or Factories to handle this. In fact it is quite easy to implement if it is a true REST API using $resource. If it is not a RESTful resource, you can use $http for custom queries

I solved this problem with $emit.
In the HTML file, upon pressing the submit button for the "Add a contact" form, two events are triggered (separated by the apostrophe button).
ng-click="addcontact(contactsignupdata.name);$emit('MyEvent')"
</form>
{{successmessage}}
In the controller file:
$scope.successmessage = null;
$scope.tpl = {};
$scope.tpl.partialtemplate1 = 'initialcontactlist.html';
$scope.addcontact = function(value) {
$scope.contactsignupdata.$save();
$scope.successmessage = 'Saved ' + $scope.contactsignupdata.name;
$scope.contactsignupdata = new Contact();
};
$scope.$on('MyEvent', function() {
$scope.tpl.partialtemplate1 = null;
$scope.resettofullcontactslist($scope.tpl.partialtemplate1);
});
$scope.resettofullcontactslist = function(value) {
$scope.tpl.partialtemplate1 = 'initialcontactlist.html';
};

Related

Hiding page loader only after completion of data load in the page view

Currently am working with angularjs.
now i have an ng-click function,it is called when checkbox is checked or unchecked. i have a full page loader and when i click on the check box it will be displayed. It will be hidden only after loading the complete view. I tried this code and it is not working
here comes the click
<input type="checkbox"id="myId" ng-click="sampleClick(1)">
here is the js code
$scope.sampleClick = function(type) {
var param = new Object();
param.type = type;
//side bar listing
Data.post('url/testurl', param).then(function(data){
$scope.all = '';
$scope.all = angular.fromJson(data);
console.log("Contents is trying to load.");
$scope.$on('$viewContentLoaded',function(event, viewConfig){
console.log("Contents did load.");
$rootScope.setVariable = 1;
});
}, function (error) {
$rootScope.setVariable = 1;
});
}
I want to set the $rootScope.setVariable = 1 only when the view section is completely loaded.(and each time when I click on the check box)
Note : when I use $viewContentLoaded at the time of page load, it works without any issue. But when I use the same along with the ng-click function, i don't get any response.
If the view is rendered using ng-repeat, why can't you use ng-repeat directive to handle the end of render and then initiate a function call.
for example
<div ng-repeat="i in things" repeat-done>
// here you use i to render your filter with checkbox
</div>
and directive will look like
app.directive('repeatDone', function($rootScope) {
return function(scope, element, attrs) {
if (scope.$last){
//set your variables or do you job
}
};
})
You can set one flag you can set it value true/false.
for example(I am taking your example so you can understand it batter):-
$scope.loading = false;
$scope.sampleClick = function(type) {
var param = new Object();
param.type = type;
//side bar listing
Data.post('url/testurl', param).then(function(data){
$scope.all = '';
$scope.all = angular.fromJson(data);
console.log("Contents is trying to load.");
$scope.loading = true;
$scope.$on('$viewContentLoaded',function(event, viewConfig){
$scope.loading = false;
console.log("Contents did load.");
$rootScope.setVariable = 1;
});
}, function (error) {
$rootScope.setVariable = 1;
});
}
here i have take $scope.loading variable which default value is false, when you click on checkbox then it will be set to true so at that time you can show the loader and when it get the data it will be set to false so it will stops loading.
I hope you understand.

when i click on update button i got data to be updated but it gets cleared when i move to update page in angularjs

$scope.fetchDataForEditInvoice = function (row)
{
var index = $scope.gridOptions.data.indexOf(row.entity);
var InvoiceId = $scope.gridOptions.data[index].InvoiceId;
var status = angularService.FetchDataForEditInvoice(InvoiceId);
status.then(function (invoiceData) {
console.log(invoiceData);
window.location.href = "/Invoice/AddInvoice";
$scope.InvoiceDetails = invoiceData.data.InvoiceDetails;
},
function () {
alert('Error in fetching record.');
})
}
on click of update button i call following function and i got data but how i can assign it to controls on update page
save invoiceData.data.InvoiceDetails in a $rootScope variable. So it will available in all controllers.
$rootScope.InvoiceDetails=invoiceData.data.InvoiceDetails;
inject $rootScope to your controller before using it.
Use routers traversing next page.Refer Single Page Apps with AngularJS Routing]1

not updated template view -> it needs mous scroll, or clear input

I'm using angular.js with stomp-websockets,sock.js under by this tutorial http://g00glen00b.be/spring-websockets-angular/. I'm getting messages from websocket, but template view isn't refreshed after message from websocket is arrived. When I want to update template view I need to clear input box, or scroll with mouse.
$scope.initiator = false;
$scope.socket = {
client: null,
stomp: null
};
$scope.initSockets = function() {
$scope.socket.client = new SockJS('/myUrl');
$scope.socket.stomp = Stomp.over($scope.socket.client);
$scope.notifyMessage = function(message) {
$scope.initiator = true;
$scope.messages.push(message)
};
$scope.socket.stomp.connect({}, function() {
$scope.socket.stomp.subscribe("/topic/messages", $scope.notifyMessage);
});
$scope.socket.client.onclose = $scope.reconnect;
};
$scope.initSockets();
template view:
<ul><li ng-repeat="item in messages track by $index">{{item}}</li></ul>
You probably need to use scope.$apply to have it take effect. afaics sock.js is not made for angular, so you need to let angular know something has changed on the scope. You do this using scope.$apply.
$scope.notifyMessage = function(message) {
$scope.$apply(function(){
$scope.initiator = true;
$scope.messages.push(message)
});
};

angularjs binding/scope issue for select list?

OK switching my code to angularjs and the angular 'way', not sure what I am doing wrong.
A select list is not getting updated when the model changes unless I call $apply, and I find myself calling apply a lot.
index.html has this:
<div id='rightcol' data-ng-include="'partials/rightSidebar.html'"
data-ng-controller="rightSidebarController">
</div>
and rightSidebar.html has this:
<select id='srcList' size='10'
data-ng-model="data.source"
data-ng-click='srcOnclick()'
data-ng-options="s.title for s in data.srcList | filter:{title:data.srcFilter} | orderBy:'title'"></select>
rightSidebarController.js has this:
$scope.data = {};
$scope.data.srcList = dataProvider.getSourceList();
$scope.data.source = dataProvider.getSource();
dataProvider is a service that makes an asynchronous database call (IndexedDB) to populate srcList, which is what gets returned in dataProvider.getSource().
Is it the asynchronous database call that forces me to call $apply, or should the controller be ignorant of that?
Is there a 'better' way to do this?
Edited to add service code.
Another controller calls dataProvider.refreshSourceList:
myDB.refreshSourceList = function() {
myDB.getRecords("source", function(recs) {
myDB.srcList = recs;
$rootScope.$broadcast('SrcListRefresh');
});
};
myDB.srcList is the field being bound by $scope.data.srcList = dataProvider.getSourceList();
myDB.getRecords:
myDB.getRecords = function(storeName, callback) {
var db = myDB.db;
var recList = [];
var trans = db.transaction([storeName], 'readonly');
var store = trans.objectStore(storeName);
var cursorRequest = store.openCursor();
cursorRequest.onerror = myDB.onerror;
cursorRequest.onsuccess = function(e) {
var cursor = cursorRequest.result || e.result;
if (cursor === false || cursor === undefined) {
if (callback !== undefined) {
$rootScope.$apply(function() {
callback(recList);
});
}
} else if (cursor.value !== null) {
recList.push(cursor.value);
cursor.continue();
}
};
cursorRequest.onerror = myDB.onerror;
};
Anything you do async needs to be wrapped in $scope.$apply(). This is because angular works in a similar fashion to a game loop, however instead of constantly running, it knows to end the loop when an action is taken, and $scope.$digest() is called.
If you are using IndexedDB, I would recommend creating an angular wrapper for it, like so:
(forgive my IndexedDB code, I'm not experience with it)
angular.module('app',[])
.factory('appdb', function($rootScope){
var db = indexedDB.open('appdb', 3);
return {
get : function(table, query, callback) {
var req = db.transaction([table])
.objectStore(table)
.get(query);
req.onsuccess(function(){
$rootScope.$apply(function(){
callback(req.result);
});
});
}
};
});
This way you can be sure that any data retrieve and set on a controller scope inside of callback will have $scope.$digest() called afterward.

AngularJS: example of two-way data binding with Resource

I have a view Transaction which has two sections
a.) view-transaction
b.) add-transaction
both are tied to the following controller
function TransactionController($scope, Category, Transaction) {
$scope.categories = Category.query(function() {
console.log('all categories - ', $scope.categories.length);
});
$scope.transactions = Transaction.query();
$scope.save = function() {
var transaction = new Transaction();
transaction.name = $scope.transaction['name'];
transaction.debit = $scope.transaction['debit'];
transaction.date = $scope.transaction['date'];
transaction.amount = $scope.transaction['amount'];
transaction.category = $scope.transaction['category'].uuid;
//noinspection JSUnresolvedFunction
transaction.$save();
$scope.transactions.push(transaction);
console.log('transaction saved successfully', transaction);
}
}
, where Transaction is a service and looks as follows
angular.module('transactionServices', ['ngResource']).factory('Transaction', function($resource) {
return $resource('/users/:userId/transactions/:transactionId', {
// todo: default user for now, change it
userId: 'bd675d42-aa9b-11e2-9d27-b88d1205c810',
transactionId: '#uuid'
});
});
When i click on tab "Transaction", the route #/transactions is activated, causing it to render both sub-views a.) and b.)
The question that I have is,
- Is there a way to update the $scope.transactions whenever I add new transaction? Since it is a resource
or I will have to manually do $scope.transactions.push(transaction);
My very first answer so take it easy on me...
You can extend the Transaction resource to update the $scope.transactions for you. It would be something like:
angular.module( ..., function($resource) {
var custom_resource = $resource('/users/:userId/transactions/:transactionId', {
...
});
custom_resource.prototype.save_and_update = function (transactions) {
var self = this;
this.$save(function () {
transactions.push(self);
});
};
return custom_resource;
});
In you controller, you would then do:
function TransactionController (...) {
...
$scope.save = function () {
...
// In place of: transaction.$save(), do:
transaction.save_and_update($scope.transactions);
...
}
}
Note: You need to make sure that object you created is fully usable in $scope. I spent 30 min trying to figure why this method failed on my code and it turn out that I am generating identity code in the database. As result, all my subsequent action on added new object failed because the new object was missing the identity!!!
There is no way to update a set of models in the scope automatically. You can push it into the $scope.transactions, or you can call a method that updates $scope.transactions with fresh data from the server. In any case, you should update the $scope in the success callback of your resource save function like this:
transaction.$save({}, function() {
$scope.transactions.push(transaction);
//or
$scope.transactions = Transaction.query();
});
In your example, when you push the transaction, you cannot be sure that the model has been saved successfully yet.
Another tip: you can create the new Transaction before you save it, and update the model directly from your view:
$scope.newTransaction = new Transaction();
$scope.addTransaction = function() {
$scope.newTransaction.save( ...
}
And somewhere in your view:
<input type="text" ng-model="newTransaction.name" />
The ng-model directive ensures that the input is bound to the name property of your newTransaction model.

Resources