Change URL hash while scrolling - javascript

I've seen some jQuery plugins for this, but I was wondering if anybody did a service or a directive that does this. Google isn't helping.
Basically, what I'd like is for the URL to update every time I go over an element with (say, a directive and) an id so that if I go to another part of the application and click back I'm returned to the header that I was reading.

Use $anchorScroll and $location
These too services should give you the desired result.
The $location service allows you to change and get the # in the url
Where as the $anchorScroll lets you pin point places in the DOC.
here is a plunker demo
And here is the main controller
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function ($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
})(window.angular);
Best of luck

Related

AngularJS $location.path() not reloading data of the destination view

In my angular project, when changing the path with $location.path('/foobar') the destination view is displayed but the data aren't reloaded (typically after saving an item and going back to the list, the list is not updated).
I tried to add $route.reload() or $scope.apply(), but nothing change.
I don't know what's wrong or missing to make this work.
UPDATE
$location.url() doesnt' work either
I'm using angular 1.2.26
UPDATE 2 - ANSWER
Ok, after a lot of comments and answers, I think it's time to end this.
I didn't think it would have been a so complicated question.
So, my conclusion, giving all you said is :
Giving simple example of #yvesmancera, the default behavior of the controller is to reload itself
In a complex controller with a resource factory and some REST calls, any save or update action should also manually update the list reference, or trigger a full reload of the list
All of you gave me some good advices, so thank you.
Use $window.location.href. to reload the page. I just check on $location document:
Page reload navigation
The $location service allows you to change only the URL; it does not allow you to reload the page. When you need to change the URL and reload the page or navigate to a different page, please use a lower level API, $window.location.href.
Example:
$window.location.href = "/your/path/here";
I had the same problem just yesterday, if you try to navigate to the same path you're already in, angular won't try to reload the view and controller. What fixed it for me is appending a "/" at the end of each route in $routeProvider, e.g:
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when('/About/', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/Contact/', {
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
})
Edit
Here is a working plunkr with angular 1.2.26
http://plnkr.co/edit/jkGKKCp0djN6Jvy2fIRd?p=preview
Pseudo Code:-
app.controller('myController', ['$scope', '$location','$http', 'ItemListService'
function($scope, $location, $http, ItemListService){
$scope.data = function(){
ItemListService.getAllItems(); //get all the items;
};
$scope.saveMethod = function(item){
$scope.data = ItemListService.save(item); //this is the refresh part, return data through save method. Pull the latest data and bind it to the scope.
$location.path('/fooView'); //dont think you even need this if you are entering data in a modal sorta thing, which on the same view.
}
}]);
You service should look like,
app.service('ItemListService', function(){
this.getAllItems = function(){
//get the items from itemList
//return all the items
}
this.save = function(item){
//save the item in itemList
//**return all items again, call getAllItems here too.
}
});
Hope this helps!!
You can switch https://github.com/angular-ui/ui-router it has method $state.reload() which can re-initialize whole controller.
If you dont want to switch ther is problem that controller is still living but you can implement after save
$rootScope.$broadcast('data:updated', $scope.data);
then wrap method of loading data in controller to function and then you can push new data to existing list / or make ajax reload
$rootScope.$on('data:updated',function(listener,data) {
$scope.data.push(data);
});
$rootScope.$on('data:updated',function()
{
callAjax.then(function(data) {
$scope.data = data;
}
});
https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$on
Try $scope.dataModel.$save(); $location.url('/foobar'); Another reason might solve the problem is: when you redirect to /foobar, the controller of foobar should have a AJAX call to your server to load the new data. And you should use angular factory to make your AJAX calls. If it is still not working, can you give more information about the version of the angular you are using, as well as your backend framework and database.
$location.path("/login");
$timeout(() => $scope.$apply(), 1000);
works for me

How to can angularjs controller access functions in a non-angularjs iframe?

I'm trying to have an angularjs controller access javascript functions in a non-angularjs iframe. I don't know where to start. Looking for guidance.
normally to communicate with an iFrame is to use window.postMessage, which enables cross-origin communcation, and on the receiving end, in your case, the window which has your angular code, you can use angular.element($window).on("message", function() to do whatever you want.
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
angular.element($window).on("message", function(e){
alert(e.data);
});
}]);
A sample js fiddle is the following. Obviously I cannot really use an iFrame, so i used a button to fake the message
http://jsfiddle.net/atozaxsv/22/
Let me know

AngularJS $location.search() not working

It's the first time I'm trying to use the $location service in AngularJS in order to check for query string arguments. I've been reading the docs and trying to play a bit with it in Plunkr to see how to use it, but so far I've failed to get it to retrieve any parameters from the query string.
I've been testing it using this plunk http://plnkr.co/edit/RIFdWa5ay2gmRa6Zw4gm?p=info
var app = angular.module('myApp', [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true);
});
angular.module('myApp').controller('myCtrl', function($scope, $location){
$scope.name = "Andrei";
$scope.url = $location.host();
$scope.path = $location.path();
$scope._params = $location.search();
});
I've read that setting html5Mode(true) on the $locationProvider is required in order to get the $location service to work as "expected" - which I've done, but when setting this nothing works anymore in my plunk (you can set it to false and you'll see the binding are qorking again properly).
Am I missing something regarding the $location service?
Any help or suggestions are appreciated!
Thanks!
In AngualarJS 1.3 $location in HTML5 mode requires a <base> tag to be present so that it knows the path that all of the links are relative to. You can add <base href="/" /> to get it working again.
http://plnkr.co/edit/j9rd1PajNLQVJ8r4c8BZ?p=preview

Checking for current route in directive

When a webpage loads for the first time, controller of my directive needs to know what is the currently selected route.
After first load I can detect change using
$scope.$on('$routeChangeSuccess', function(){});
EDIT:
Answers below are valid but it didn't work for me because:
- I am new to AngularJS technology i didn't realize that, on our project, we are using custom route provider
- You need to inject 'ngRoute' in your module before you can use $route
You can use the $routeChangeSuccess callback signature
function(event, currentRoute, previousRoute) {}
PLUNKER
e.g.
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
console.log(current.$$route); // displays current $route object
});
The current documentation does not show the callback signatures(IDK why) but you can see them on their github, see this line.
you need to inject $route dependency in your controller and then get the current route using $route.current
Plunker Example
Controller code snippet:
.controller('MainController', function($scope, $route, $routeParams, $location) {
//Here setting scope with $route object
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})

Angular reload Template + Controller without using Routes

I want to reload a template and the connected Controller without using $routeProvider, because
my Path-structure doesn't fit with .when(...). I want to use $location.path() to read the URL and set the desired action.
But: if the path of the URL changes, the template doesn't automatically update and neither is the controller reloaded.
Is there a way to say something like this?
angular.module('myApp').controller('ctrl').reload()
I would suggest looking into the Angular UI Router written by the same guys who wrote angular. It will let you transition to different states which is what it sounds like you are trying to do.
https://github.com/angular-ui/ui-router
My solution: don't use Routes! Simply update a variable for your template, controllers don't need updates (simply update the data):
angular.module('myApp',[])
.run(['$rootScope', '$location', 'myService', function ($rootScope, $location, myService) {
$rootScope.view = "";
// Some function to read the URL
$rootScope.setRouting = function(){
var p = $location.path().split("/");
// Do things with p[0], p[1], ...
// e.g. if url is /post/123
$rootScope.view = p[0];
myService.setData(p[1]);
}
// Monitor Location changes:
$rootScope.$on('$locationChangeSuccess', function(event) {
$rootScope.setRouting();
});
// And this is useful for calling within template: ng-click="go('...')"
$rootScope.go = function(path){
$location.path(path);
}
}]);
And for the HTML:
<body>
<ng-include src="view + '.html'"></ng-include>
</body>

Categories

Resources