AngularJS controller called every time after ngRoute url is clicked - javascript

I have problem with below code. When I go to main controller url #/, Angular naturally calls main controller - it execute AJAX request. Problem is, that when I click #/some-url, and then #/ url again, this AJAX request is executed again, which is not desired and unnecessary due to performance. I thought controllers are called only once, but it doesn't look like this is the case, at least with ngRoute.
angular.module('robotsApp', ['ngRoute', 'controllers'])
.config(['$routeProvider', function($routeProvider){
var root = '/static/js/partials/';
$routeProvider.
when('/', {
templateUrl: root + 'main.html',
controller: 'main as main'
}).
when('/some-url', {
templateUrl: root + 'some_template.html',
controller: 'someController'
}).
otherwise({
redirectTo: '/'
});
}]);
angular.module('controllers', [])
.controller('main', ['$http', function($http){
$http.get('/user/recent-gain-loss').success(function(data){
this.recent_gain_loss = data;
}.bind(this));
}]);
<p>{{ main.recent_gain_loss }}</p>

Save the data in to a value and then check if the data are already set.
angular.module('values', [])
.value('recentGainLoss', {})
angular.module('controllers', ['values'])
.controller('main', ['$http', 'recentGainLoss', function($http, recentGainLoss){
if (Object.keys(recentGainLoss).length < 1) {
$http.get('/user/recent-gain-loss').success(function(data){
recentGainLoss = angular.extend(recentGainLoss, data);
});
}
this.recent_gain_loss = recentGainLoss;
}]);

Related

How to use view in angular js on other page after $location.path?

This is my app.js
var mainApp = angular.module("myapp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/search/login.html'
}).
when('/dashboard', {
templateUrl: 'admin/index.html'
}).
otherwise({
redirectTo: '/'
});
}]);
mainApp.controller('logincntrl',function($scope,$location){
$scope.submit=function(){
var uname=$scope.username;
var upass=$scope.password;
if($scope.username=="admin" && $scope.password=="admin"){
$location.path('/dashboard');
}
};
});`
After clicking on submit.It will redirect to dashboad..That is seperate folder with index.But as i have given view on the first page ..my dashboard contain coming on the first page even with styling..how to make seperate view for dashboard page
You can use <ng-view><ng-view> to have load different
partials. You can have a look into this to have an ideahttp://codepen.io/dhanrajjay/pen/dOjmxL/

Routing is not working in AngularJS app

I am making an angularjs app but my routing part is not working.
Once I login into application using Login.html,it should route to index.html but it is not working.
app.js
/**
* Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'index.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}]);
I uploaded all my custom files at below location.
http://plnkr.co/edit/mi2JS4y2FfMD9kIl58qk?p=catalogue
I have already included all the dependency files like angular.js and angular-route.js etc..
Thanks in advance.
Here is a working plunker based on your code. You are missing the ng-view that the ngRoute will replace based on your config. So, the index.html looks like:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ng-view></ng-view>
</body>
ng-view is an Angular directive that will include the template of the current route (/main or /home/student) in the main layout file. In plain words, it takes the file based on the route and injects it into the main layout (index.html).
In the config, ng-view will be replace by 'main' that points to Login.html. I change the '/home/student/' to point to a new page 'dic.html' to avoid infinite loop as it used to point to index.html
var app = angular.module('plunker', ['ngRoute', 'Controllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'dic.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}
]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
Like your example, if one logs in with 'harish' as an e-mail and 'harish' as a password, the successCallback is called and goes to '/home/student' that replaces ng-view by dic.html:
$scope.validate = function() {
$http.get('credentials.json').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Data: ' + JSON.stringify(response));
$scope.users = response.data;
var count = 0;
for (var i = 0, len = $scope.users.length; i < len; i++) {
if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
alert("login successful");
count = count + 1;
if ($scope.users[i].role === "student") {
$location.path('/home/student');
break;
}
}
}
if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error: " + JSON.stringify(response));
alert(JSON.stringify(response));
});
};
Let us know if that helps.
You need to add ng-view in the index.html inside the ng-app.
Something like..
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Now, the angular app would assign the view template and controller as defined by your routes configuration, INSIDE the ng-view directive.
Also, should have a generic index.html where all dependencies are included, and render the templates & assign them controllers in accordance with routes configurations. No need to create separate files which includes the dependencies all over again, like you did with index.html and login.html.
You have not injected $location in your controller.
app.controller('MainCtrl', function($scope, $http, $location) {
$scope.name = 'World';
});

Controller not loading up

I have the following Index.html file (I put div with ng-view as well):
<ul ng-controller="myController">
<li>
Do it!
</li>
</ul>
routes config:
$routeProvider.when('/doit', {
templateUrl: 'partials/doit.html'
controller: 'myController'
});
$routeProvider.otherwise({
redirectTo: 'index.html'
});
Controller:
app.controller('myController', ['$scope', '$location', function ($scope, $location) {
$scope.name = "name";
alert($scope.name);
$location.path("/");
}]);
The weird thig is that after I click on the Do it! link, it goes to http://localhost:3000/#/doit.html (the code of myController executes after the click, I see the alert pop-up), and then I go back to http://localhost:3000/#/index.html (this is what I want, I put $location.path("/") in the controller.
However, this time, for some reason, the controller code doesn't execute. It only runs after I refresh the page, even though it is assigned to the unordered list. Could anyone help please?
Your routes config should be something like:
$routeProvider.
when('/', {
templateUrl: '/index.html',
controller: 'homeCtrl'
}).
when('/doit', {
templateUrl: 'partials/doit.html',
controller: 'myController'
}).
otherwise({
redirectTo: '/'
});
and you do not need to specify controller name at two places i.e. in the partial and in your route config, specifying at the config level should be sufficient.
The doit view should be the one which is loaded in the ng-view tag as it is a state of your application.

$scope does not return any value

I am trying to access $scope variable inside my controller . when I console my $scope it shows number of values but when I try to access it via $scope. it return undefined.
I have attached screen shot of $scope
Here you can see it have $id, $parent , templateUrl but when i am trying to access it via $scope.id , $scope.parent , $scope.templateUrl it return undefined .
Edited :
I am trying to access template url . actually I want to attach some params with template url so that I can get them in my backend function
here is my code :
brainframeApp.config(
['$interpolateProvider', '$locationProvider', '$httpProvider', '$routeProvider',
function($interpolateProvider, $locationProvider, $httpProvider,
$routeProvider) {
//configuring angularjs symbos to not to conflict with Django template symbols
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
//$locationProvider.html5Mode(true).hashPrefix('!');
// setup CSRF support
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
console.log("TestDavy: App");
//The route provider
$routeProvider.
when('/', {
templateUrl: '/static/engine/partials/listbrainframes.html',
controller: 'brainframeCtrl'
}).
when('/brainframe/', {
templateUrl: '/views/post.html',
controller: 'brainframeCtrlx'
}).
when('/brainframe/:id', {
templateUrl: '/views/post.html',
controller: 'brainframeCtrlx'
}).
otherwise({
redirectTo: '/'
});
}]);
my controller :
brainframeAppControllers.controller('brainframeCtrlx',
['$scope', '$routeParams', function($scope, $routeParams) {
//console.log($scope.parent);
//$scope.templateUrl = 'views/post.html?id='+$routeParams.id;
//console.log($scope);
$scope.templateUrl = 'views/post.html?id='+$routeParams.id;
//console.log($scope.templateUrl);
}]);
When I put console.log on $scope, am able to see only these properties:
["$$childTail", "$$childHead", "$$nextSibling", "$$watchers", "$$listeners", "$$listenerCount", "$id", "$$ChildScope", "$parent", "$$prevSibling"]
If you want to access the template URL inside your controller:
brainframeApp.run(function($rootScope) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
$rootScope.templateUrl = next.$$route.templateUrl;
});
});
Now inside your controller, inject $rootScope and get the template URL
$rootScope.templateUrl

Multiple Controllers for one view angularjs

I would like to know if it is possible to use multiple controllers for a single url view using angluarjs, I have not been able to find much documentation on this. I would like to use a controller on all pages to switch the page header title, but some pages already contain a controller
app.js
subscriptionApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/billinginfo',{templateUrl:'views/billing-info.html', controller:'billingInfoController'}).
when('/orderreview',{templateUrl:'views/order-review.html', controller:'billingInfoController'}).
when('/subscribed',{templateUrl:'views/subscribed.html', controller:'subscribedTitle'}).
//EXAMPLE: HOW COULD I ADD TWO CONTROLLERS TO SAME PAGE??? THIS DOES NOT WORK
when('/subscribe',{templateUrl:'views/subscribe.html', controller:'subscriptionController', 'testControllerTitle'}).
when('/unsubscribed',{templateUrl:'views/cancelconfirm.html', controller:'unsubscribedTitle'}).
when('/redirectBack',{templateUrl:'views/redirect-to-app.html'}).
when('/redirectHandler',{templateUrl:'views/redirect-handler.html',controller:'redirectController'}).
when('/error',{templateUrl:'views/error.html', controller:'messageController'}).
otherwise({redirectTo:'/subscribe'});
}]);
EDIT
I am trying to add a title controller to each page view:
function testControllerTitle($rootScope, $scope, $http) { $rootScope.header = "Success!"; }
If I add this controllers to the pages that don't already have a controller it works, if there is another controller in place I can't make this work.
<h1 ng-bind="header"></h1>
Yes, controllers and templates are independent, check this http://jsbin.com/wijokuca/1/
var app = angular.module("App", ['ngRoute']);
app.config( function ( $routeProvider ) {
$routeProvider
.when('/a', {templateUrl: 'this.html', controller: "aCtrl"})
.when('/b', {templateUrl: 'this.html', controller: "bCtrl"})
.when('/c', {templateUrl: 'that.html', controller: "bCtrl"})
.otherwise({redirectTo: '/a'});
});
app.controller('aCtrl', function ($scope) {
$scope.all = [1,2,3];
});
app.controller('bCtrl', function ($scope) {
$scope.all = [4,5,6];
});

Categories

Resources