How to get AngularJS to respond to navigation - javascript

I am designing a site which has a fixed data set (17 records - each representing a 'book' for sale) and allows navigation between several pages that display details about each of the books. The problem I am having is that when the hyperlink goes to a different view, everything works fine, but if it is hyperlink is to a different book of the same view, it fails to run the controller script. How do I force this to be done.
I have made a minimal executable example:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var fooApp = angular.module('fooApp', []);
fooApp.controller('fooCtrl', function ($scope) {
$scope.books = ["Book1", "Book2", "Book3", "Book4", "Book5"]
$scope.selectedBook = "Book1";
var curPath = window.location.toString();
var hashPos = curPath.indexOf("#/");
if (hashPos>0) {
$scope.selectedBook = curPath.substring(hashPos+2);
}
});
</script>
</head>
<body ng-app="fooApp" ng-controller="fooCtrl">
Selected Book: {{selectedBook}}
<ul>
<li ng-repeat="book in books">Visit A {{book}}
</li>
</ul>
<ul>
<li ng-repeat="book in books">Visit B {{book}}
</li>
</ul>
</body></html>
Save the above to two different files: PageA.htm and also as PageB.htm. The selected book is passed as a parameter after the hash mark. You will see the behavior as this: When on PageA you can click on a link to PageB and the book is selected appropriately. But if you click on a link to PageA the URL changes in the address bar, but the controller function does not apparently run. Similarly, on PageB, links to PageA will select a book, but links that stay on PageB do not.
I like the fact that the page is NOT re-read from the server ... it comes out of cache, but I would like to somehow trigger the the controller function again so that the new passed parameter can be read and the correct data displayed. What am I doing wrong?
Update One
Some have suggested to add target="_self" to the hyperlink tag. This works in the simplified minimal example above. Unfortunately, it does not work on fully elaborated site. I don't know why. You can check the full site and the problem is that the "Featured-Book" does not display if you are showing the details of any other book.

Ok. It seems you need to use the $location service and $locationChangeSuccess event in order to keep track url changes. These are part of the Angular core API.
fooApp.controller('fooCtrl', function ($scope, $rootScope, $location) {
$scope.books = ["Book1", "Book2", "Book3", "Book4", "Book5"]
$scope.selectedBook = "Book1";
$rootScope.$on('$locationChangeSuccess', function (event, location) {
$scope.selectedBook = $location.path().substring(1);
});
});

It seems that you are trying to implement a route system.
Have you looked into Angular's ngRoute? check out this example.
ngRoute is great because you can access route data via its $route service or simply via $routeParams.

Related

Python Flask Web App Navigation Without Page Refresh

I Want to develop a flask navigation bar like Google Contacts.
I Want to Render a particular HTML page inside the red box (as in the picture) when I click each of the navigation buttons (the green box as in picture) without refreshing the page.
I have already tried using
{% extends "layout.html" %}
As #Klaus D. mentioned in the comments section, what you want to achieve can be done using Javascript only. Maybe your question were
How can I send a request to my server-side (to get or fetch some information) and receive back a response on the client-side without having to refresh the page unlike the POST method usually does?
I will try to address the aforementioned question because that's probably your case.
A potential solution
Use Ajax for this. Build a function that sends a payload with certain information to the server and once you receive back the response you use that data to dynamically modify the part of the web-page you desire to modify.
Let's first build the right context for the problem. Let's assume you want to filter some projects by their category and you let the user decide. That's the idea of AJAX, the user can send and retrieve data from a server asynchronously.
HTML (div to be modified)
<div class="row" id="construction-projects"></div>
Javascript (Client-side)
$.post('/search_pill', {
category: category, // <---- This is the info payload you send to the server.
}).done(function(data){ // <!--- This is a callback that is being called after the server finished with the request.
// Here you dynamically change parts of your content, in this case we modify the construction-projects container.
$('#construction-projects').html(data.result.map(item => `
<div class="col-md-4">
<div class="card card-plain card-blog">
<div class="card-body">
<h6 class="card-category text-info">${category}</h6>
<h4 class="card-title">
${item.title_intro.substring(0, 40)}...
</h4>
<p class="card-description">
${item.description_intro.substring(0, 80)}... <br>
Read More
</p>
</div>
</div>
</div>
`))
}).fail(function(){
console.log('error') // <!---- This is the callback being called if there are Internal Server problems.
});
}
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Flask (Server-side)
''' Ajax path for filtering between project Categories. '''
#bp.route('/search_pill', methods=['POST'])
def search_pill():
category = request.form['category']
current_page = int(request.form['current_page'])
## Search in your database and send back the serialized object.
return jsonify(result = [p.serialize() for p in project_list])
Thank you #CaffeinatedCod3r,#Klaus D and #newbie99 for your answers.
I Figured it out. instead of using Flask we can use Angular JS Routing for navigation.
Here is the example that i referred:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<head>
<base href="/">
</head>
<body ng-app="myApp">
<p>Main</p>
Banana
Tomato
<p>Click on the links to change the content.</p>
<p>Use the "otherwise" method to define what to display when none of the links are clicked.</p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/banana", {
template : "<h1>Banana</h1><p>Bananas contain around 75% water.</p>"
})
.when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95% water.</p>"
})
.otherwise({
template : "<h1>Nothing</h1><p>Nothing has been selected</p>"
});
$locationProvider.html5Mode(true);
});
</script>
</body>
</html>
By Using $locationProvider.html5Mode(true) i was able to remove the # from the URL.

Change AngularJS url/route from html - javascript code

Say I have a button that's within the ng-app scope, but outside the ng-controller/ng-view scope.
<html ng-app="myApp">
<!-- ... -->
<body>
<button id="myButton">Click me!</button>
<div ng-view> <!-- angular-view --> </div>
</body>
</html>
And I want to change the URL/Route when I click the button.
var button = document.getElementById('myButton');
button.addEventListener('click', function() {
//code that changes path.
});
How do I do that? If I try window.location.href = '/'; the whole page gets reloaded, not just the view. $location isn't visible from html javascript, so that's not an option neitehr.
If anyone knows a way I can change the path/route/url from javascript, I'd be more than happy to accept any valid answer, or a redirect to some helpful documentary post, or a rederect to another SO question, because I'm trying to find an answer to this for a while and I've got nothing...
I'll note that I tried making a global scope function, but that didn't work, neither.
angular.module('myApp', [])
.config( ... )
.run(function($rootScope, $location) {
$rootScope.setUrl = function(url) {
$location.path(url);
};
})
.controller(
.....
and called with setUrl('/');, $root.setUrl('/'); and $rootScope.setUrl('/');, but still nothing ('undefined').
note: the button script is just an example, the real purpose why I'm asking this is a little bit larger, so I'm trying to simplify.
If your purpose is to change route from outside of the Angular app, then you need to change location hash part:
window.location.hash = 'new-route';
Inside Angular controller use $location.path method.

How to update title of the SPA in angularjs?

To be noted:
The site that I am talking here is SPA and using angularjs.
Say I have music site. Now there are n number of albums.
Hindi
English
Bhajans
My requirement is if user clicks on Hindi Albums, the title of the page should be set to Hindi, if he clicks on English title should be updated to English and so on.
Plus,how do I change the og tags as well as every albums has social share buttons so I need to update the og tags as well.
If you say that I can set the title while configuring routes,that doesn't works in my scenario.
Scenario
.when('/albums',
{
templateUrl: 'Angular-Templates/albums.html',
controller: 'albumsCtrl',
caseInsensitiveMatch: true,
title: 'Albums'
})
Now albumsCtrl in turns calls db function and fetches the list of availbles albums. Now user will click on any of the fetched albums and title should be updated to the name of the album,
FYI:-
I am NOT using angular.ui, but core angular.
You could define controller at the level.
<html ng-app="app" ng-controller="titleCtrl">
<head>
<title>{{ Page.title() }}</title>
...
<a ng-click="page">
You create controller:
angular.controller('$scope',
function($scope) {
var title = 'default';
$scope.page = function(data) {
title = data;
}
});
Inject Page and Call 'Page.setTitle()' from controllers.
In order to update the title of the browser in JavaScript, you should utilize the document.title property.
Example:
in controller
$scope.setTitleHindi = function() {
document.title = "Hindi";
}
and in your template
<span ng-click="setTitleHindi">Click Me!</span>

Same controller for multiple ng-app

I have a single webpage, that have different documents.php, each document with its ng-app and some controllers. (My webpage is similat to spotify).
player.php: (Where the user can play some music with an audio player)
<div class="navbar-fixed" ng-controller="menuController as menu2">
<?php include('includes/menu.php'); ?>
</div>
<div ng-controller="InteractiveController as interactCtrl">
//some code
</div>
panel_admin.php: (where the user can modify its data and some data of the webpage)
<div class="navbar-fixed" ng-controller="menuController as menu2">
<?php include('includes/menu.php'); ?>
</div>
<div ng-controller="AdminController as AdminCtrl">
//some code
</div>
player.php and panel_admin.php have its respective player.js and panel_admin.js with its .controllers.
player.js:
var decibelsInteractive = angular.module("decibels-interactive", []);
decibelsInteractive.controller('InteractiveController', function ($scope, $log) {
panel_admin.js:
var adminControl = angular.module("decibels-admin", []);
adminControl.controller("AdminController", function($scope){
Now, I have the menu bar in menu.php, where I use in player.php, and in panel_admin.php document. I import it because I don't want to repeat code in every page where I need to use the menu (menu.php have options like manage user options, logout, and many others...). I also have created a menu.js to only have the specific methods in one document and not in 25 documents.
menu.php: (menu is a menu bar where the user have some options, and it also have its username and logout option)
//this document only contains some html code
Now, I've tried to implement a simple code (in menu.js) that allows me to share one controller when I have many ng-app.
Question with the code I've taken
menu.js:
angular.module('decibels-interactive', ['shared']); //player2.php
angular.module('decibels-admin', ['shared']); //panel_admin.php
var sharedModule=angular.module('shared',[]);
sharedModule.controller('menuController',['$scope',function($scope) {
alert("menuController");
}]);
});
And this worked!!! But then, angular shows an error... (loading player.php)
Error: [ng:areq] http://errors.angularjs.org/1.2.25/ng/areq?p0=InteractiveController&p1=not%20a%20function%2C%20got%20undefined
And when I load panel_admin the same error appears again, but with the AdminController...
It seems like that angular only detects the first controller in each .php, and can't find the second one.
What am I doing wrong?
Thank you!
You can create a file for your shared code and have the controller code inside it.
// #file mySharedCode.js
var MySharedCode = MySharedCode || {};
MySharedCode.menuController = function($scope) {
// controller logic
};
Then, in your app.js file call menuController function
// #file app.js
sharedModule.controller('menuController', MySharedCode.menuController);

How to setup ngclass change when route change occurs in AngularJS?

I am trying to add a class on my main .container class when the route changes.
My current simple solution involves an ng-click on every main menu url (no other urls on the page):
app.controller('MainCtrl', ['$scope', function( $scope ){
$scope.setMain = function( value ){ $scope.isMain = value };
}]);
Then in my html:
<div ng-controller="MainCtrl" class="container" ng-class="{'main': isMain}">
<ul class="main-menu">
<li><a href="#" ng-click="setMain(true)"></li>
<li><a href="#/page-1" ng-click="setMain(false)"></li>
<li><a href="#/page-2" ng-click="setMain(false)"></li>
</ul>
<div ng-view></div>
</div>
This seems to work ok as long as I need to add any more urls the problem is when a user does not click on any of the links and directly accesses a url he does not get the main class.
Is there a better way to do this?
You could use a few different options, but I think the easiest for you would be to setup the $scope.isMain value on controller initialisation by looking at $location. So inside the controller you could have something like:
var loc = $location.path();
if(loc === /* some route rule you require */){
$scope.isMain = true;
}
Have a look here: http://docs.angularjs.org/api/ngRoute/service/$route as the example down the bottom has a few different examples of what sort of data you can access with regards to the route.

Categories

Resources