why angularjs controller loading twice - angularjs

Here is my route config, I am using routeProvider to bind controller to view and not declaring ng-controller in my view still my controller loading twice, I searched for lot of solutions and tried every thing but no use.
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "app/views/home.html"
}).when("/login", {
controller: "loginController",
templateUrl: "app/views/login.html"
}).when("/regcars", {
controller: "RegCarsController",
templateUrl: "app/views/client/RegCars.html"
}).otherwise({ redirectTo: "/home/" });
Here is template(view)
<div class="col-md-6 box box-success pull-left">
<div class="box-header with-border">
<h3 class="box-title">My cars</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
{{CarName}}
</div>
</div>
And here is my controller
app.controller('RegCarsController', function ($scope) {
$scope.CarName = "MyCar";
alert('MyCar');
});
In my above code showing alert twice. Below I have link to call the view, tried with and with out slash at end of href link
<a href="#/regcars/">
<i class="fa fa-car fa-2x"></i> <span>My Cars</span>
</a>

Some proof of concept that controller is called many times. Strange.
On the other hand - the same code on JSFiddle - shows that controller is executed / fired only once.
angular.module('app', ['ngRoute']).config(function($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "app/views/home.html"
}).when("/regcars", {
controller: "RegCarsController",
templateUrl: "app/views/client/RegCars.html"
}).otherwise({ redirectTo: "/home" });
})
.run(function($templateCache) {
$templateCache.put('app/views/home.html', '<div>home tempalte</div>');
$templateCache.put('app/views/client/RegCars.html', '<div>cars template, car name: {{ CarName }}</div>');
})
.controller('homeController', function() {})
.controller('RegCarsController', function($scope) {
$scope.CarName = "MyCar";
console.log('Called many times')
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script>
<div ng-app='app'>
<ul><li><a href='#/'>Home</a></li><li><a href='#/regcars'>Cars</a></li></ul>
<ng-view></ng-view>
</div>

Related

Always show 1 view outside of ng-view - angular

I have the following controllers, and I want the template of the CategoryController to be shown on all pages (ie with all other views). the app displays all categories with this controller, when you click a category it shows all books in that category, then when you click a book it shows the books details. I want the categories to be always shown, can this be done ng-include?
app.config(function ($routeProvider) {
$routeProvider
.when('/books', {
controller: 'BookshelfController',
templateUrl: 'views/bookshelf.html'
})
.when('/books/:bookId', {
controller: 'BookController',
templateUrl: 'views/book.html'
})
.when('/categories', {
controller: 'CategoryController',
templateUrl: 'views/categories.html'
})
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
.otherwise({
redirectTo: '/books'
});
});
html
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
As #Hadi says, use angular-ui-router, or why not just place the controller directly over the view when it should be shown on every page, anyway?
<div class="main">
<div class="container">
<div ng-controller="CategoryController"></div>
<div ng-view></div>
</div>
</div>

ngView with Node.js doesn't load the main page when the ULR is reloaded

In the first load everything is okay but, when I reload/refresh the page the main page don't load and only the template load.
I use Node.js and express for route pages I think when I try reload page:
app.get('/', function (req, res) {
res.render('index.html');
console.log('GET: 200 index');
console.log(req.statusCode);
<div class="container conteudo btn-group btn-group-lg" ng-controller="routeCtl">
<a class="btn btn-default" ng-class="{active: isActive('/cadastro/cadastro')}" href="/cadastro/cadastro">{{lnkCadastrar}}</a>
<a class="btn btn-default" ng-class="{active: isActive('/login/login')}" href="/login/login">{{lnkAcessar}}</a>
<a class="btn btn-default" ng-class="{active: isActive('/home/home')}" href="/home/home">{{lnkHome}}</a>
</div>
<div ng-view class="container divNgView"></div>
This is my route:
var appRoute = angular.module('appRoute', ['ngRoute'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.when('/footer', {
templateUrl: '../views/footer.ejs'
}).when('/login/login', {
templateUrl: '../views/login/login.html',
controller: 'loginCtl'
}).when('/cadastro/cadastro', {
templateUrl: '../views/cadastro/cadastro.html',
controller: 'cadastroControll',
controllerAs: 'cadastroCtl',
reloadOnSearch: false
}).when('/home/home', {
templateUrl: '../views/home/home.html',
controller: 'homeControll'
}).when('/*', {
templateUrl: '../views/error.ejs'
});
$routeProvider.otherwise({
}).otherwise({
redirectTo: '/index.html',
reloadOnSearch: false
});
$locationProvider.html5Mode({enabled: true, requireBase: false});
}]);
appRoute.controller('appRouteCtl', ['$scope', function ($scope) {
$scope.title = "Controlador de Patio";
}]);

Angular Routes not working, can you spot the bug?

I am trying to route 2 partials to my index page, but so far only one route seem to work, the other is unresponsive. I have gone through the codes so many times, but can't seem to spot the issue. Would appreciate any insights.
Heres are my controllers:
app.controller('HomeController', ['$scope','stream', function($scope, stream) {
stream.then(function(data) {
$scope.photos = data;
});
}]);
This is the controller for the partial that fails to load
app.controller('PhotoController', ['$scope','stream', '$routeParams', function($scope, stream, $routeParams) {
stream.then(function(data) {
$scope.descript = data.items[$routeParams.photoid];
});
}]);
This is the
<div class="container" ng-repeat="photo in photos.items" >
<div class="photo" >
<div>
<img class="col-md-2 thumbnail" ng-src="{{photo.media.m}}">
</div>
<div class="col-md-8" style="height: 119px; width: 641px">
<div class="row" id="title"><p1>{{photo.title}}</p1></div>
<div class="row list-desc">
<p1 id="author">{{photo.author}}</p1>
<p1 id="pub-date">Published:{{photo.published | date}}</p1>
<a id="view-link" href="description/{{$index}}">View on flickr</a>
</div>
</div>
</div>
</div>
This is the one that fails to load.
<div class="container" ng-repeat="desc in descript" >
<h1>{{desc.title}}</h1>
</div>
This is my routing:
var app = angular.module('angularOne', ['ngRoute']);
app.config(['$routeProvider','$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
controller: 'HomeController',
templateUrl: 'views/home.html'
}).
when('/description/:photoid', {
controller: 'PhotoController',
templateUrl: 'views/photo.html'
}).
otherwise({
redirectTo:'/'
});
$locationProvider.html5Mode(true);
}]);
desc should descript in the html, or the other way around in the js.

Angular, redirect from one controller to onother

I'm developing an application using angularjs starting from https://github.com/firebase/angularfire-seed project. I'm trying to redirect from a controller to another without success. I need to do this from controller because i have some controls to do before redirect. I'm using location object for do it..
Here is my code for redirect:
$scope.infostore = function() {
$location.path( 'store' );
}
Here is my route configuration:
angular.module('myApp.routes', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/home', {
authRequired: true,
templateUrl: 'partials/home.html',
controller: 'HomeCtrl'
});
$routeProvider.when('/apps', {
authRequired: true,
templateUrl: 'partials/apps.html',
controller: 'appsController'
});
$routeProvider.when('/store', {
authRequired: true,
templateUrl: 'partials/store.html',
controller: 'storeController'
});
$routeProvider.otherwise({redirectTo: '/home'});
}]);
But every time i call the method 'infostore' in appsController angular redirect me to 'home'
Why? I just try to use apply() without success on main scope.
Here is my store controller:
'use strict';
app.controller('storeController', function($location, $firebase, $modal, $scope, database, $http, $rootScope, $routeParams) {
var ref = database.returnRef("users/"+$rootScope.auth.user.uid+"/apps");
$scope.apps = $firebase(ref);
});
Here is store html:
<div class="container">
<br />
<div class="row">
<div class="col-md-12 text-center">
<h3>
<span>{{ 'myappslong' | translate }}</span>
</h3>
</div>
</div>
<br />
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
store
</div>
<div class="col-md-1"></div>
</div>
</div>
Here is the URL from the first controller: http://localhost:8000/app/index.html#/apps
Solved, there was an error in my html code. Using location.path works correctly.

routeProvider in angularJS not acting right

Within my view I am outputting links. When I go to click a link it triggers the otherwise method in my routeProvider and ends up redirecting back to home. I need it to redirect indiv id and I need to be able to grab project.id from my view within my controller. May I please have some assistance. I'm kind of stuck.
My view:
<div class="container clearfix">
<div class="pagename sixteen columns fadeInUp animated">
<h1 style="font-family: Merriweather">Portfolio</h1>
</div>
</div>
<div class="container clearfix" ng-controller="portfolioController">
<ul style="padding-left: 20pt" class="large-block-grid-4 align-center">
<li class="part" ng-repeat="project in projects">
<a href="#/indiv?id={{ project.id }}">
<img src="{{ project.screenshot_uri }}" alt="">
</a>
<br><br>
<h4>{{ project.project_name }}</h4>
<p>{{ project.description }}</p>
</li>
</ul>
</div><br><br>
My app data:
var app = angular.module("app", ['ngRoute']).config(function($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'index.php/projects/projects/home',
controller: 'homeController'
});
$routeProvider.when('/portfolio', {
templateUrl: 'index.php/projects/projects/portfolio',
controller: 'portfolioController'
});
$routeProvider.when('/indiv:id', {
templateUrl: 'index.php/projects/projects/indiv',
controller: 'indiv_controller'
});
$routeProvider.when('/contact', {
templateUrl: 'index.php/projects/projects/contact',
controller: 'contactController'
});
$routeProvider.otherwise({ redirectTo: '/home' });
});
app.factory('pull_projects', function($http) {
return {
get_projects: function(callback) {
$http.get('index.php/projects/pull_projects').success(callback);
}
};
});
app.controller('portfolioController', function($http, $location, $scope, pull_projects) {
pull_projects.get_projects(function(results) {
$scope.projects = results;
});
});
app.controller('contactController', function($http, $location, $scope) {
});
app.controller('indiv_controller', function($http, $location, $scope, $routeParams) {
alert($routeParams.id);
});
app.controller('homeController', function($http, $location, $scope) {
});
Seems the problem is that you are defining the angular routing url and the url in the markup slightly different.
Route:
In the route url you are defining /indiv:id. However, this would match a url where the id was part of the indiv part. So, http://host/indiv123.
So, I would suggest changing this to: /indiv/:id. This will then match urls like this: http://host/indiv/123.
Markup:
In the HTML you are declaring the url as #/indiv?id={{ project.id }}. This will produce the url: /indiv?id=123.
To match our new angular route we need the template to be #/indiv/{{ project.id }} so that we produce a url like /indiv/123.
Hope this helps.
You should use :
ng-href="#/indiv?id={{ project.id }}"
instead of
href="#/indiv?id={{ project.id }}"
This ensures that {{ project.id }} is correctly resolved before it is used as a link.
This occurs because Angular not always gets the chance to intercept the data binding requests before the browser attempts to resolve href and src (<img src="">) attributes. Accordingly, you should use ng-src for images.

Resources