Angular JS deep linking will refresh view - javascript

I'm going to try my best to explain this problem. I am also new to Angular so bear with me.
I have two routes that use the same template...
ExampleApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/logbook/following', {
templateUrl: 'views/surf.html',
})
.when('/logbook/following/:surf_id', {
templateUrl: 'views/surf.html',
})
}]);
with two controllers
AppControllers.controller('LogbookController', function($scope, $http, $location, $routeParams) {
$scope.surfs = null;
// Get feed
$http.get(RestURL + 'feeds?filter=following' ).success(function(data) {
if(typeof $routeParams.surf_id == "undefined") {
if(data.length > 0) {
$location.path('/logbook/following/' + data[0].id);
$scope.loadSurfDetail(data[0].id);
}
}
$scope.surfs = data;
});
});
AppControllers.controller('SurfController', function($scope, $http, $location, $routeParams) {
$scope.loading = false;
// Load surf
$scope.loadSurfDetail = function(surfID) {
$scope.loading = true;
$scope.selectedSurf = null;
// Get surf
$http.get(RestURL + 'surfs/' + surfID).success(function(data) {
$scope.selectedSurf = data;
$scope.loading = false;
});
};
if($routeParams.surf_id) {
$scope.loadSurfDetail($routeParams.surf_id);
}
});
using this template file:
<div class="row">
<div class="logbook col-md-3" ng-controller="LogbookController">
<h1>Logbook</h1>
<ol class="surfs-feed">
<li data-id="{{feedSurf.id}}" ng-repeat="feedSurf in surfs" class="surf">
<a href="#/logbook/following/{{feedSurf.id}}">
<strong>{{feedSurf.user.first_name}} {{feedSurf.user.last_name}}</strong>
</a>
</li>
</ol>
</div>
<div class="surf col-md-9" ng-controller="SurfController">
<p class="alert alert-info" ng-show="loading">
Loading...
</p>
<div class="surf-detail" ng-show="selectedSurf">
<pre>
{{selectedSurf | json}}
</pre>
</div>
</div>
</div>
My issue is that when I load a deep link URL, ie. /logbook/following/:surf_id it will use the same template as /logbook/following (adove) and that will cause the logbook feed to be regenerated each time you load up a new surf. So each time you load the surf, the logbook "blinks" and regenerates.
I would like to know how people have tackled this problem without refreshing the feed of surfs and just updating the detail panel on the right hand side...
Thanks!

In your app config, inject $locationProvider and set its html5Mode parameter to true. Then, route changes will not cause the page to refresh.
ExampleApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/logbook/following', {
templateUrl: 'views/surf.html',
})
.when('/logbook/following/:surf_id', {
templateUrl: 'views/surf.html',
})
$locationProvider.html5Mode(true);
}]);

Related

First ng-view template's controller not loading

My landing page component's controller doesn't retrieve any data when the app initially loads or when I reload from the landing page. I keep getting undefined for my variables when I have verified there is data.
If I click on the #/index link, the data loads fine and my variable logs to the console. Any idea why this happens to only the initial load of the webpage and when I reload it on the landing?
Edit: Added the appUser value that I am trying to log along with the app's main controller. Essentially, I run a service via appStore to retrieve user details. I then set my appUser value. I have confirmed the appStore service works.
It seems like the MainLandingCtrl runs before the AppCtrl
app.module.js:
angular.module('dup', ['ngRoute', 'mainLanding', 'unauthorized']);
app.value.js
angular.module('dup')
.value('appUser', {
fup: undefined
});
app.controller.js
angular.module('dup')
.controller('AppCtrl', ['appStore', 'appUser', '$log', function(appStore, appUser, $log) {
var rcAppTemp = this;
// User authorization
appStore.authorizedUser()
.then(function(response) {
rcAppTemp.userDetails = response.data;
appUser.fup = rcAppTemp.userDetails.fup;
}, function(error) {
$log.log('error');
});
}]);
app.config.js:
angular.module('dup')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Main page
.when('/', {
template: '<main-landing></main-landing>'
})
.when('/unauthorized', {
template: '<unauthorized></unauthorized>'
})
.otherwise({
redirectTo: '/'
});
}]);
main-landing.controller.js:
angular.module('mainLanding')
.controller('MainLandingCtrl', ['appUser', '$log', function(appUser, $log) {
var mn = this;
mn.fup = appUser.fup;
$log.log(mn.fup);
}]);
main-landing.component.js
angular.module('mainLanding')
.component('mainLanding', {
bindings: {
},
templateUrl: 'components/main-landing/main-landing.template.html',
controller: 'MainLandingCtrl'
});
index.html:
<body ng-app="dup">
<div ng-controller="AppCtrl as app">
<!-- navigation bar (excluded for brevity) -->
</div>
<div ng-view></div>
</body>
main-landing.template.html
<div class="row">
<div class="small-12 medium-4 medium-offset-4 large-4 large-offset-4 columns">
<div title="Home">
<h5>Dup</h5>
<ul>
<li><strong>Index</strong></li>
<li ng-show="$ctrl.fup><strong>Trouble</strong></li>
</ul>
</div>
</div>
</div>

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';
});

Sending a $routeParam to the server through a service Angular

You will have to bear with me because I am a self-taught noob.
I have a php page on my server that need a $_get variable to sort the data on the server side rather than the client. I am using routeParams in Angular for the variable to send over. This works, however it only works when you refresh the webpage. Please can someone help me as my head hurts from hitting the wall.
Controller:
app.controller('JuiceController', ['$scope', 'juices', function($scope, juices) {
juices.success(function(data){
$scope.juices = data;
});
}]);
Service:
app.factory('juices', ['$http', '$routeParams',function($http, $routeParams) {
return $http.get('http://madcow-app.dev/application/backend/api/products.php', {
params: {prod: $routeParams.prod}
})
.success(function(data) {
return data;
})
.error(function(err){
return err;
});
}]);
Html output (juice view):
<div class="juice-wrap" ng-repeat="juice in juices">
<div class="juice-img"><img ng-src="{{ juice.imgpath }}" width="163" height="176" alt=""/></div>
<div class="juice-rght">
<div class="juice-title">{{ juice.name }}</div>
<div class="juice-desc">{{ juice.descrip }}</div>
Route provider
$routeProvider
.when('/', {
templateUrl: 'script/views/home.html'
})
.when('/categories/', {
controller: 'CatController',
templateUrl: 'script/views/categories.html'
})
.when('/juice/:prod', {
controller: 'JuiceController',
templateUrl: 'script/views/juice.html'
})
.when('/events/', {
controller: 'EventController',
templateUrl: 'script/views/events.html'
})
.when('/qr/', {
templateUrl: 'script/views/qr.html'
})
.when('/feedback/', {
templateUrl: 'script/views/feedback.html'
})
.otherwise({
redirectTo: '/'
php function outputs json (this is outputted to the php controller below and takes the category id as a variable:)
return json_encode($results);
To the php controller (this is the page that the angular service/factory pulls the json array of products from:
<?php
include "../../init.php";
if (isset($_GET['prod']))
{
echo $MC->Api->getProductsApi($_GET['prod']);
}
else
{
echo 'error';
}
This is the category html:
<div class="cat-btn" ng-repeat="cat in cats">
<a href="#/juice/{{cat.catid}}">
<img ng-src="{{ cat.imgpath }}" width="363" height="195" alt=""/>
<div class="cat-btn-text"> {{ cat.name }} </div>
</a>
basically what I want to achieve is when a user clicks a category in the frontend, angular routes to the product view using the category id as a filter for the php function to populate the json output with only the juices in that category.
I'm not sure if I should be doing it this way around, or whether I need to hit it from another angle. Please bear in mind that i am a complete javascript noob and laymans would be great for the answer.
Thank you in advance.....
Factory:
app.factory('juices', [
'$http', '$routeParams', function ($http, $routeParams) {
var self = this;
function getJuices() {
$http.get('http://madcow-app.dev/application/backend/api/products.php', {
params: {prod: $routeParams.prod}
})
.success(function (data) {
self.juices = data.data;
})
.error(function (err) {
});
}
return {
getJuices: getJuices,
juices: self.juices
}
}
]);
Controller:
app.controller('JuiceController', [
'$scope', 'juices', function ($scope, juices) {
juices.getJuices();
$scope.$watch(function () {
return juices.juices
}, function (newJuices, oldJuices) {
// This is triggered when juices.juices changes
// newJuices containes the juices retrieved from server
// This is needed because it is asynchronous
});
}
]);

How should I get the data from JSON into another angular js controller?

I'm new to AngularJS and stuck on below code.
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/home.html",
controller: "mainController",
})
.when('/products', {
templateUrl: "partials/productlist.html",
//controller: "ProductController",
})
.when('/product/:prodID', {
templateUrl: "partials/product.html",
controller: "viewController",
})
.when('/contact', {
templateUrl: "partials/contact.html",
controller: "contactController",
})
.otherwise({
redirectTo: "/"
});
});
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams){
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
And my product.html page code will look like this.
<div ng-controller="viewController">
<ol class="breadcrumb">
<li>Home</li>
<li>Products</li>
<li class="active">{{eachproduct.link}}</li>
</ol>
<div class="col-md-4">
<figure><img ng-src="{{ }}"></figure>
<p>
Read More
</p>
</div>
</div>
Problem is when I navigate to any product page value of {{eachproduct.link}} is not showing.
Any solution will be appriciated.
Use $rootScope instead of $scope
$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.
Sample :
controller('viewController',['$scope','$routeParams', '$http','$rootScope',function($scope,$routeParams, $http,$rootScope){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$rootScope.eachproduct = $scope.datap[$routeParams.prodID];
});
}]);
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
});
It seems like what you are looking for is an angular provider such as a factory to store the values in, this will allow the values to be pass values around the controllers while using the routes.
Have a look at this example, while it isn't using routes, the principal is the same:
https://jsbin.com/wiwejapiku/edit?html,js,output
For more information on providers have a look here:
https://docs.angularjs.org/guide/providers
Your example would work something like this:
app
.factory('productFactory',function(){
return {
data: {}
};
})
.controller('ProductController', function($scope, $http, productFactory){
$scope.productFactory = productFactory;
$http.get('partials/productTable.json').success(function(response){
$scope.productFactory.data = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, productFactory){
$scope.productFactory = productFactory;
$scope.eachproduct = $scope.productFactory.data[$routeParams.prodID];
});
Note you would also have to change your view to reference 'productFactory.data' respectively.

Angular UI-Router not showing html content, but directing to the right path. No errors, but ui-view not working

I am using UI-Router for an Angular app. I can't seem to find what I am doing wrong. I am also not getting any errors which is making it really difficult for me to debug. Followed the docs as well and I am following their steps. My controller function is working when I don't nest it in a child view. Can someone please direct me to what I am doing wrong? Thanks in advance!
APP.JS
'use strict';
var app = angular.module('americasTopStatesApp', ['ui.router', 'ngAutocomplete']);
app.run(function($state, $rootScope) {
$rootScope.$state = $state;
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise('/home');
$stateProvider
//HOME
.state('home', {
url: '/home',
templateUrl: './app/views/homeTmpl.html',
controller: 'homeCtrl'
})
//RANKINGS
.state("rankings", {
url: "/rankings",
templateUrl: './app/views/rankingsTmpl.html',
controller: 'rankingsCtrl'
})
// RANKINGS CHILDREN
.state('rankings.data', {
url: '/data',
templateUrl: './app/views/rankingsDataTmpl.html',
controller: 'rankingsCtrl',
parent: 'rankings'
})
});
CONTROLLER rankingsCtrl
'use strict';
app.controller('rankingsCtrl', function($scope, rankingsService) { //Start Controller
// ***********************************************
// *************** GET LATEST DATA ***************
// ***********************************************
$scope.getAllStateRankings = function() {
rankingsService.getStateRankingsData().then(function(data) {
$scope.showRankings = true;
// console.log("Contoller Data", data);
$scope.states = data;
});
};
$scope.showRankings = false;
$scope.getAllStateRankings();
}); //End Controller
PARENT VIEW rankingsTmpl.html
<div class="rankings-heading">
<h1>America's Top States</h1>
<button ng-click="getAllStateRankings()">
<a ui-sref="rankings.data" id="data" class="btn">Data</a>
</button>
</div>
</div ui-view></div>
Child View (Nested ui-view) rankingsDataTmpl.html
<div class="rankings-container" ng-show="showRankings">
<div class="panel panel-primary" ng-repeat='state in states'>
<div class="panel-heading">
<h3 class="panel-title">{{state.state}}</h3>
</div>
<div class="panel-body">
Economy: {{state.economy}}<br>
Capital Access: {{state.accessToCapital}}<br>
Business: {{state.business}}<br>
Cost of living: {{state.costOfLiving}}<br>
</div>
</div>
</div>
Screen Shot
There is a working plunker
In this case, when we have parent child and angular's UI-Router, we should not use solution based on
parent and child has same controller. // WRONG approach
Because they in fact do have JUST same type. The instance of that type 'rankingsCtrl' in runtime is different.
What we need is:
How do I share $scope data between states in angularjs ui-router?
scope inheritance, driven by reference object, e.g. $scope.Model = {}
There is adjusted controller:
.controller('rankingsCtrl', ['$scope', function($scope) {
$scope.Model = {};
$scope.getAllStateRankings = function() {
//rankingsService.getStateRankingsData().then(function(data) {
$scope.Model.showRankings = true;
// console.log("Contoller Data", data);
$scope.Model.states = data;
//});
};
$scope.Model.showRankings = false;
$scope.getAllStateRankings();
}])
At the end, child can have different controller with its own logic for the child view:
.state("rankings", {
url: "/rankings",
templateUrl: 'app/views/rankingsTmpl.html',
controller: 'rankingsCtrl'
})
// RANKINGS CHILDREN
.state('rankings.data', {
url: '/data',
templateUrl: 'app/views/rankingsDataTmpl.html',
controller: 'rankingsChildCtrl',
parent: 'rankings'
})
Also, the parent view should have fixed div:
// wrong
</div ui-view></div>
// starting tag
<div ui-view></div>
Check it here in action

Categories

Resources