Suppose I have a table such that it adds rows when user click a button. The row adding code looks like this:
success: function (data, textStatus, jqXHR) {
$row = $('a#temp').parents('table').find('tr[id$=' + m + ']');
var $new_rows = $(data['payload'].join("\n"));
$row.after($new_rows);
}
Whereas the success is a non-angular callback function such that the ajax response has came back.
The payload will contain the HTML code along with the controller and directive inside the HTML.
I saw that the row is added correctly but I don't see the newly added row controller and directive get initialize.
Any suggestion is welcome.
Thanks
Even though this is a very bad idea, as #tymeV mentioned in their comment, you should be able to do what you want using the $compile service.
Just inject $compile into whatever function contains the AJAX call and (so long as you also have the $scope available), you can change your success handler to:
success: function (data, textStatus, jqXHR) {
$row = $('a#temp').parents('table').find('tr[id$=' + m + ']');
var $new_rows = $(data['payload'].join("\n"));
$row.after($new_rows);
$compile($new_rows)($scope);
// if this is definitely the success handler for a jQuery.ajax() request or similar
// then do the following. Otherwise, remove it.
$scope.$digest();
}
This should be a last resort though. You really need to try and abandon relying on jQuery, especially to do DOM manipulation, and use the Angular directives instead. It will be much easier for you and anyone else who has to look at and maintain your code to understand.
Remember the old adage, "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability." (see this question for who said this). The violent psychopath who knows Angular will not think fondly of you for committing this cardinal sin in terms of AngularJS development.
Related
While transitioning an existing angular site, I encountered an annoying problem. The initial symptom was that a certain controller was not running it's initialize function immediately following the login. I logged and I tracked, and eventually I realized it was a design flaw of the page. Essentially, index.html contains a <header>, <ng-view>, and <footer>. There are a couple of ng-if attributes that live in the header that I want to evaluate after the login, but since the view is the only thing that is reloaded, it was not reinitializing the header controller, and thus not updating the ng-if values.
Then I was reminded of ngInclude, which seems like the perfect solution, until I got it hooked up and realize that doesn't work either. It loads the template the first time, and doesn't reinitialize when the view changes. So then I got the bright idea of passing the HeaderController to another controller or service, and controlling this one stubborn boolean value through a proxy of sorts. That also didn't work. Then I tried putting a function and a boolean into another service, and mirroring that property in the header controller, but thus far I have not gotten this working.
I have done plenty of research about multiple views in the index, and so far I hear a lot about this ui-router, but I'm still not convinced that is the way I want to go. It does not seem to be a simple solution. I have not tried putting the ng-include into the templates yet either, because then I feel like that is going back in time to when we had to update 100 pages every time we changed the menu.
I lost a whole day to this. If anyone could tell me how to trigger the evaluation of this one property in my header controller which I would like to live outside the other templates, please let me know!
Ok so you need to know in your HeaderController when the view has reloaded. There's a number of ways of doing this but the easier and maybe the more correct in this particular case is with an event.
So when you are refreshing the view you just do this, let's say you need the new value of ob1 and ob2 variables.
// ViewController
$rootScope.$emit('viewRefresh', {ob1: 'newvalue1', ob2: 'newvalue2'});
And in your HeaderController you need to listen for that event, and set on your $scope the new values for those attrs (if you're not using controller as syntax).
// HeaderController
$rootScope.$on('viewRefresh', function onRefresh(event, data) {
$scope.ob1 = data.ob1;
$scope.ob2 = data.ob2;
})
Another Solution
Sharing a Promise through a Service (using $q)
function HeaderService($q) {
var defer = $q.defer();
return {
getPromise: function() {return defer.promise},
notify: function(data) {defer.notify(data)}
}
}
function HeaderController(HeaderService) {
var vm = this;
HeaderService.getPromise().then(function(data) {
vm.ob1 = data.ob1;
vm.ob2 = data.ob2;
})
}
function ViewController(HeaderService) {
var data = {ob1: 'newvalue1', ob2: 'newvalue2'};
HeaderService.notify(data)
}
I am trying to call an API end point once a user clicks a button holding a myNavigator.pushPage() request. However,I can not get the $scope data generated from the $http.get request to be passed to the new page.
If I test using console.log('test'); inside the .success of the $http.get request I successfully get the log info in the console but any data held in $scope.var = 'something'; does not gets passed to the page! Really confused!
$scope.historyDetails = function(id){
var options = {
animation: 'slide',
onTransitionEnd: function() {
$http.get('http://xxx-env.us-east-1.elasticbeanstalk.com/apiget/testresult/testId/'+id).success(function(data) {
$scope.testscore = 'something'; // this is not getting passed to page!
console.log('bahh'); // But I see this in console
});
}
};
myNavigator.pushPage("activity.html", options);
}
Page:
<ons-page ng-controller="HistoryController">
...
<span style="font-size:1.2em">{{testscore}} </span><span style="font-size:0.5em;color:#555"></span>
...
</ons-page>
Yes, that's so because both pages has different controllers, resulting in different scopes. One can not access variables from one scope to another.
Hence one solution in this case can be using rootScope service.
Root Scope is parent scope for all scopes in your angular application.
Hence you can access variable of root scopes from any other scope, provided that you are injecting $rootScope service in that controller.
to know more about rootScope check this link.
Good luck.
Update 1:
check these articles
http://www.dotnet-tricks.com/Tutorial/angularjs/UVDE100914-Understanding-AngularJS-$rootScope-and-$scope.html
https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
As Yogesh said the reason you're not getting your values is because if you look at $scope.testscore and try to find where is the $scope defined you will see that it's an argument for the controller function (thus it's only for that controller).
However we can see that the controller is attached to the page and you are pushing another page.
So in that case you have several options:
Use the $rootScope service as Yogesh suggested (in that case accept his answer).
Create your own service/factory/etc doing something similar to $rootScope.
(function(){
var historyData = {};
myApp.factory('historyData', function() {
return historyData;
});
})();
Technically you could probably make it more meaningful, but maybe these things are better described in some angular guides.
If you have multiple components sharing the same data then maybe you could just define your controller on a level higher - for example the ons-navigator - that way it will include all the pages. That would be ok only if your app is really small though - it's not recommended for large apps.
If this data is required only in activity.html you could just get it in that page's controller. For example:
myApp.controller('activityController', function($scope, $http) {
$http.get(...).success(function(data) {
$scope.data = data;
});
}
But I guess you would still need to get some id. Anyway it's probably better if you do the request here, now you just need the id, not the data.
You could actually cheat it with the var directive. If you give the activity page <ons-page var="myActivityPage"> then you will be able to access it through the myActivityPage variable.
And the thing you've been searching for - when you do
myNavigator.pushPage("activity.html", options);
actually the options is saved inside the ons-page of activity.html.
So you can do
myNavigator.pushPage("activity.html", {data: {id: 33}, animation: 'slide'});
And in the other controller your id will be myActivityPage.options.data.id.
If you still insist on passing all the data instead of an id - here's a simple example. In the newer versions of the 2.0 beta (I think since beta 6 or 7) all methods pushPage, popPage etc return a promise - which resolve to the ons-page, making things easier.
$scope.historyDetails = function(id){
myNavigator.pushPage("activity.html", {animation: 'slide'}).then(function(page) {
$http.get('...' + id).success(function(data) {
page.options.data = data;
});
});
});
Side note: You may want to close the question which you posted 5 days ago, as it's a duplicate of this one (I must've missed it at that time).
In my MEANJS app. I am setting the value of a scope variable to a query result, from my controller function
$scope.myVar = User.query();
console.dir($scope.myVar); //Returns all the documents from the DB correctly
console.log('User's name is : ' + $scope.myVar[0].name); //This comes as undefined
Somehow, in the very next line when I am trying to open the name field within the same controller function, it comes as undefined. Also, the entire result is being read absolutely correctly in my view file. So when I call
{{myVar.name}}
within my view file it outputs the name correctly. I cannot understand this behavior at all. This is my first time working with Angularjs, and I could have missed something basic, but I appreciate any help at this point.
Edit - Also the length of $scope.myVar is always 0 within the controller
Basically User.query() returns a promise object, so you need to update you $scope object inside promise success.
Code
User.query().$promise.then(function(res){
//you will get response here in data obj
$scope.myVar = res;
console.dir($scope.myVar);//Returns all the documents from the DB correctly
console.log('User's name is : ' + $scope.myVar[0].name); //This comes as undefined
});
EDIT: Found the answer. The callback functions in meanjs are in this format:
var myObj= User.query(function(response) {
console.log('Inside success response');
//Can access myObj values here easily
}, function(errResponse) {
console.log('Inside error response ' + errResponse);
});
I wasn't able to figure out how to access my $scope.myVar within the controller, but I completed a workaround by creating my own factory method to retrieve data the way I wanted it sorted. The problem of not being able to access these query results is really posing a problem in other parts as well. So if anyone has an answer, please do let me know.
For now posting the link I used to figure out how the MEAN.JS factory method needs to be plugged in. Hope this helps someone.
https://groups.google.com/forum/#!searchin/meanjs/query()/meanjs/4R7rIolH9bs/P1R4YlKgowUJ
I am trying to use the ebay api in an angular.js app.
The way the api works by itself is to pass data to a callback function and within that function create a template for display.
The problem that I am having is in adding the data returned from the callback to the $scope. I was not able to post a working example as I didnt want to expose my api key, I am hoping that the code posted in the fiddle will be enough to identify the issue.
eBayApp.controller('FindItemCtrl', function ($scope) {
globalFunc = function(root){
$scope.items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
console.log($scope.items); //this shows the data
}
console.log($scope.items); //this is undefined
})
http://jsfiddle.net/L7fnozuo/
The reason the second instance of $scope.items is undefined, is because it is run before the callback function happens.
The chances are that $scope.items isn't updating in the view either, because Angular doesn't know that it needs to trigger a scope digest.
When you use the Angular provided async APIs ($http, $timeout etc) they have all been written in such a way that they will let Angular know when it needs to update it's views.
In this case, you have a couple of options:
Use the inbuilt $http.jsonp method.
Trigger the digest manually.
Option number 1 is the more sensible approach, but is not always possible if the request is made from someone else's library.
Here's an update to the fiddle which uses $http.jsonp. It should work (but at the moment it's resulting in an error message about your API key).
The key change here is that the request is being made from within Angular using an Angular API rather than from a script tag which Angular knows nothing about.
$http.jsonp(URL)
.success($scope.success)
.error($scope.error);
Option 2 requires you to add the following line to your JSONP callback function:
globalFunc = function(root){
$scope.items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
console.log($scope.items); //this shows the data
$scope.$apply(); // <--
}
This method tells Angular that it needs to update it's views because data might have changed. There's a decent Sitepoint article on understanding this mechanism, if you are interested.
I have a webapp written in AngularJS which basically polls an API to two endpoints. So, every minute it polls to see if there is anything new.
I discovered that it has a small memory leak and I've done my best to find it but I'm not able to do it. In the process I've managed to reduce the memory usage of my app, which is great.
Without doing anything else, every poll you can see a spike in the memory usage (that's normal) and then it should drop, but it's always increasing. I've changed the cleaning of the arrays from [] to array.length = 0 and I think I'm sure that references don't persist so it shouldn't be retaining any of this.
I've also tried this: https://github.com/angular/angular.js/issues/1522
But without any luck...
So, this is a comparison between two heaps:
Most of the leak seems to come from (array) which, if I open, are the arrays returned by the parsing of the API call but I'm sure they're not being stored:
This is basically the structure:
poll: function(service) {
var self = this;
log('Polling for %s', service);
this[service].get().then(function(response) {
if (!response) {
return;
}
var interval = response.headers ? (parseInt(response.headers('X-Poll-Interval'), 10) || 60) : 60;
services[service].timeout = setTimeout(function(){
$rootScope.$apply(function(){
self.poll(service);
});
}, interval * 1000);
services[service].lastRead = new Date();
$rootScope.$broadcast('api.'+service, response.data);
});
}
Basically, let's say I have a sellings service so, that would be the value of the service variable.
Then, in the main view:
$scope.$on('api.sellings', function(event, data) {
$scope.sellings.length = 0;
$scope.sellings = data;
});
And the view does have an ngRepeat which renders this as needed. I spent a lot of time trying to figure this out by myself and I couldn't. I know this is a hard issue but, do anyone have any idea on how to track this down?
Edit 1 - Adding Promise showcase:
This is makeRequest which is the function used by the two services:
return $http(options).then(function(response) {
if (response.data.message) {
log('api.error', response.data);
}
if (response.data.message == 'Server Error') {
return $q.reject();
}
if (response.data.message == 'Bad credentials' || response.data.message == 'Maximum number of login attempts exceeded') {
$rootScope.$broadcast('api.unauthorized');
return $q.reject();
}
return response;
}, function(response) {
if (response.status == 401 || response.status == 403) {
$rootScope.$broadcast('api.unauthorized');
}
});
If I comment out the $scope.$on('api.sellings') part, the leakage still exists but drops to 1%.
PS: I'm using latest Angular version to date
Edit 2 - Opening (array) tree in an image
It's everything like that so it's quite useless imho :(
Also, here are 4 heap reports so you can play yourself:
https://www.dropbox.com/s/ys3fxyewgdanw5c/Heap.zip
Edit 3 - In response to #zeroflagL
Editing the directive, didn't have any impact on the leak although the closure part seems to be better since it's not showing jQuery cache things?
The directive now looks like this
var destroy = function(){
if (cls){
stopObserving();
cls.destroy();
cls = null;
}
};
el.on('$destroy', destroy);
scope.$on('$destroy', destroy);
To me, it seems that what's happening is on the (array) part. There is also 3 new heaps in between pollings.
And the answer is cache.
I don't know what it is, but this thing grows. It seems to be related to jQuery. Maybe it's the jQuery element cache. Do you by any chance apply a jQuery plugin on one or more elements after every service call?
Update
The problem is that HTML elements are added, processed with jQuery (e.g. via the popbox plugin), but either never removed at all or not removed with jQuery. To process in this case means stuff like adding event handlers. The entries in the cache object (whatever it is for) do only get removed if jQuery knows that the elements have been removed. That is the elements have to be removed with jQuery.
Update 2
It's not quite clear why these entries in the cache haven't been removed, as angular is supposed to use jQuery, when it's included. But they have been added through the plugin mentioned in the comments and contained event handlers and data. AFAIK Antonio has changed the plugin code to unbind the event handlers and remove the data in the plugin's destroy() method. That eventually removed the memory leak.
The standard browser way to fix memory leaks is to refresh the page. And JavaScript garbage collection is kind of lazy, likely banking on this. And since Angular is typically a SPA, the browser never gets a chance to refresh.
But we have 1 thing to our advantage: Javascript is primarily a top-down hierarchial language. Instead of searching for memory leaks from the bottom up, we may be able to clear them from the top down.
Therefore I came up with this solution, which works, but may or may not be 100% effective depending on your app.
The Home Page
The typical Angular app home page consists of some Controller and ng-view. Like this:
<div ng-controller="MainController as vm">
<div id="main-content-app" ng-view></div>
</div>
The Controller
Then to "refresh" the app in the controller, which would be MainController from the code above, we redundantly call jQuery's .empty() and Angular's .empty() just to make sure that any cross-library references are cleared.
function refreshApp() {
var host = document.getElementById('main-content-app');
if(host) {
var mainDiv = $("#main-content-app");
mainDiv.empty();
angular.element(host).empty();
}
}
and to call the above before routing begins, simulating a page refresh:
$rootScope.$on('$routeChangeStart',
function (event, next, current) {
refreshApp();
}
);
Result
This is kind of a hacky method for "refreshing the browser type behavior", clearing the DOM and hopefully any leaks. Hope it helps.