$scope is updated, but the view is not - angularjs

I have 2 states. A home state and a child of the home state called, suggestions. The home state loads a template into a ui-view element.
Inside my home template, and my suggestions template I have this link,
.addmovie{"ng-click" => "addMovie(movie)"}
This link fires the .addMovie function. This places a new value in my database and after that's done reloads all the data with this,
var init = function(){
movieService.loadMovies().then(function(response) {
$scope.movies = response.data;
var orderBy = $filter('orderBy');
$scope.orderedMovies = orderBy($scope.movies, "release_date", false);
var movies = $scope.orderedMovies
var i,j,temparray,chunk = 8, movieGroups=[];
for (i=0,j=movies.length; i<j; i+=chunk) {
temparray = movies.slice(i,i+chunk);
movieGroups.push(temparray);
}
$scope.movieGroups = movieGroups
})
$(".search_results").fadeOut(250);
$('body').find('#search_input').val("");
movieTrailers.loadTrailers().then(function(response) {
$scope.trailers = response.data;
})
movieSuggestions.loadSuggestions().then(function(response) {
$scope.suggestions = response.data;
})
console.log ('init end')
}
So if I add a movie from within my home template, the view updates with the new data.
In this home template I also have a button that loads the suggestions state,
#suggestions
%a{"ui-sref" => ".suggestions"}
%h1
Suggestions
%div{"ui-view" => "suggestions"}
This loads the suggestions template inside the suggestions view inside the home state.
In my suggestions template I have the same button as in the home state.
.addmovie{"ng-click" => "addMovie(movie)"}
And when I click that it does do the addMovie function because I get the console logs in my console, and also it reloads all the data (with use of the init function) because when I check the network tab and view the movies.json it has the new data. But it does not update my home template view. To see the new data in my home template I have to refresh the page.

Related

How to call a method in the child window in Angular JS

My angular JS application has a view button. When clicking on the view button, it will call method and that method changes the content in the same page. Now I have a request that when clicking on the view button, it has to open in a new tab and display the contents.
Previous code:
HTML:
<md-button ng-click="ctrl.ViewClick(item)">View</md-button>
Controller:
vm.ViewClick = function(item) {
// The browser URL is same but it is a new page with the new contents.
// Calls a angular js service and loads the contents
}
Now, I need to call that function in new browser tab.
I made the following changes but didn't worked. Can you please help me on this.
HTML:
<md-button ng-click="ctrl.NewTabClick(item)">View</md-button>
Controller:
vm.newTabClick = function(item){
$Window.open($location.absURL(), 'blank');
// How do I call vm.ViewClick function after opening the new browser window?
};
This is the old angular JS. Thanks for helping on this.
On workaround you can do in this case is, While opening the page pass query parameter in the URL.
vm.newTabClick = function(item){
// Add `viewLink=true` query parameter with true value
$Window.open($location.absURL() + '&viewLink=true', 'blank');
// Store item in sessionStorage
window.sessionStorage.setItem('item', JSON.stringify(item));
}
And then from the component where you want to call the parameter. You can write below code on $onInit lifecycle hook.
vm.$onInit = function () {
// Inject $routeParams in dependency areay
const storedItem = sessionStorage.getItem('item')
if ($routeParams.viewLink == 'true' && storedItem && storedItem != 'null') {
vm.viewLink(JSON.parse(storedItem));
}
}

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

Backbonejs - Back button doesn't work if page transition on same page

Short description of my program and finally the problem:
I have got two pages. The first page list products in rows with a short description. If you click on one you will land on a detail page.
The detail page lists the product details and underneath a couple of related products. If you click on one of the releated products the same page is rendered again with the new information fetched from a REST interface.
If I want to use the browser-back-button or the own back-button to get to the previous product-detail-page a blank page appears. This only happens on my iPad. Using Chrome on a desktop browser works fine. I debugged the application and I figured out, that the backbonejs route is never called. I have no idea why.
Here is my code of the details page:
define([
"jquery",
"lib/backbone",
"lib/text!/de/productDetails.html"
],
function(
$,
Backbone,
ContentTemplate
){
var PageView = Backbone.View.extend({
// product details template
template: _.template(ContentTemplate),
// back-button clicked
events:{
'click a#ac-back-button':'backInHistory',
},
// init
initialize: function(options){
this.options=options;
// bind functions
_.bindAll(this,
'render',
'renderRelatedSeriePlainproduct',
'backInHistory'
);
// listen for collection
this.listenTo(this.options.relatedCollectionPlainproduct, 'reset',this.renderRelatedSeriePlainproduct);
},
// back button
backInHistory: function(e){
e.preventDefault();
window.history.back();
},
// render template
render: function(){
// render template
this.$el.html(this.template(this.model.models[0].attributes));
return this;
},
// render related products
renderRelatedSeriePlainproduct: function (){
var models = this.options.relatedCollectionPlainproduct.models;
if(models.length==0){
$('.ac-plainproduct').hide();
} else{
var elem = $('#ac-related-listing-plainproduct');
var ct="";
ct+='<ul id="ac-list-related-plainproduct">';
$.each(models, function(key, value){
ct+='<li>';
ct+='<a href="index.html?article_id='+value.get('article_id')+'&type='+value.get('type')+'&serie='+value.get('series')+'#product-detail">Link';
ct+='</a>';
ct+='</li>';
});
ct+='</ul>';
elem.append(ct);
}
}
});
// Returns the View class
return PageView;
});
I follow one of the links from renderRelatedSeriePlainproduct.If I click on the back button on the new page the backInHistory function is called, but the window.history.back(); does not call the backbone router.
Maybe the problem is the #hash in the URL, that is not changed during page transition. But this would not explain, why it works perfectly with my Chrome on my desktop machine. For me it seemed to be a problem of asynchronous calls but even there I could not find a problem.
Maybe it helps to list my router code as well. First of all I was thinking it is an zombie issue in backbone, but I remove all events and views while making the transition.
// function called by the route
// details page
productdetail: function() {
$.mobile.loading("show");
_self = this;
// lazy loading
require([
'collection/ProductDetailCollection',
'collection/RelatedCollection',
'view/ProductDetailView'
],
function(ProductDetailCollection, RelatedCollection, ProductDetailView){
// get URL parameters
var articleID = _self.URLParameter('article_id');
var type = _self.URLParameter('type');
var serie = _self.URLParameter('serie');
// product - details
var productDetail = new ProductDetailCollection.ProductDetail({id: articleID});
// related products
_self.relatedCollectionPlainproduct = new RelatedCollection({serie:serie, type:"Electronics", article_id:articleID});
// assign binded context
productDetail.fetch({
// data fetched
success: function (data) {
// page transition
_self.changePage(new ProductDetailView({
model:data,
relatedCollectionPlainproduct:_self.relatedCollectionPlainproduct
}));
// fetch data
_self.relatedCollectionPlainproduct.fetch({reset:true});
}
});
});
},
// page transition
changePage:function (page) {
// remove previous page from DOM
this.page && this.page.remove() && this.page.unbind();
// assign
this.page = page;
// assign page tag to DOM
$(page.el).attr('data-role', 'page');
// render template
page.render();
// append template to dom
$('body').append($(page.el));
// set transition
var transition = "fade";
// we want to slide the first page different
if (this.firstPage) {
transition = "fade";
this.firstPage = false;
}
// make transition by jquery mobile
$.mobile.changePage($(page.el), {changeHash:true, transition: transition});
// page was rendered - trigger event
page.trigger('render');
$.mobile.loading("hide");
},
I tried to use allowSamePageTransition but with no success. Maybe someone could give me a hint. Thanks!
Looks like jQuery Mobile and Backbone's routers are conflicting. Take a look here:
http://coenraets.org/blog/2012/03/using-backbone-js-with-jquery-mobile/
Thats not the reason. I disabled the routing of jquery mobile.
// Prevents all anchor click handling
$.mobile.linkBindingEnabled = false;
// Disabling this will prevent jQuery Mobile from handling hash changes
$.mobile.hashListeningEnabled = false;

Angular: how to call a function after changing state

I am building a small message system. I use tabs in my state (inbox, outbox). Also, i want to sent a message when i click a "contact" link. If i click that link, this should happen:
change state to messages state
open other tab, called "newmsg"
At this moment, this is what i have:
<a ng-click="mailContact()">contact</a>
and i my controller:
$scope.mailContact = function() {
$state.go('root.messages');
$scope.openTab('new');
};
Obviously this is not working, because $scope.openTab('new'); will never execute. The state changes to what i want, but the tab is not opened. I do not have a clue of how to get it done.
Ok, stupid thing was i had an init which opened the "inbox"...
Now i wrote a service which does the trick.
app.factory('msgTabService', ['$rootScope', function($rootScope) {
var msgTabService = {};
var tabname = "inbox";
msgTabService.set = function(tab) {
tabname = tab;
};
msgTabService.get = function() {
return tabname;
};
msgTabService.openTab = function(tab) {
if ($rootScope.currenttab !== tab)
{
$rootScope.currenttab = tab;
msgTabService.set(tab);
}
};
return msgTabService;
}]);
The question may be similar to: Save State of Tab content when changing Route with angularjs and BootStrap Tabs

still the navigate triggers and upate my url, the method is not calling

In my backbone app, i use the requirejs to load the js files. as well i need different views, there is no.of links are there in my drop down menu. according to the drop down menu i a adding the #url example:
http://localhost:85/bino/html/interface-I.html#projectName/project11
the navigate method works fine and updating the url, also whenever i copy and paste this url to any other browser / refresh with current hash state my router methods works fine.
But click on link in the drop down menu not working, the method not calling... what would be the reason and how can i fix this..?
my code: main js file (part of code)
var extender = _.extend({},backBone.Events);
var params ={
boardHolder :$('.boardHolder'),
column :3,
space :30,
extender :extender
};
var listApp = new routerer(params);
backBone.history.start();
extender.bind("list:selected",function(post){
listApp.navigate(post.category+'/'+post.filter);
});
my router code :
define(["backBone","singleton","listCollection","listView","listViews"],function(Backbone,singleton,listCollection,listView,listViews){
singleton.router = Backbone.Router.extend({
routes:{
"" :"appView",
"post" :"postView",
"projectName/:id" :"projectNameView",
"assignedTo/:id" :"assignedToView",
"sortBy/:id" :"sortByView"
},
initialize:function(params){
this.params = params;
this.collection = new listCollection;
console.log('i am called');
},
hashView:function(){
console.log('from hash view');
},
appView:function(){
var that = this;
// var defaultApp = new listCollection();
this.collection.fetch({
success:function(data){
new listViews({model:data,params:that.params})
}
})
},
projectNameView:function(thisView){ // not calling not sync
console.log('called',thisView); // on click not works
},
assignedToView:function(thisView){ // not calling not sync
console.log(thisView); // on click not works
},
sortByView:function(thisView){ // not calling not sync
console.log(thisView); // on click not works
}
});
return singleton.router;
})
thanks in advance.
navigate only updates the url, you also have to call the route function by setting the trigger option to true. If you'd like to update the URL without creating an entry in the browser's history, also set the replace option to true.
listApp.navigate(post.category+'/'+post.filter);
would become
listApp.navigate(post.category+'/'+post.filter, {trigger: true});

Resources