0

http://jsfiddle.net/fhfepbtu/

I'd like to parse the current url and use the parsed values in the application. How can I set a model variable to the current URL?

Here's the code from the fiddle link.

HTML:

<div ng-controller="MyCtrl">
  {{url}}
</div>

JS:

var myApp = angular.module('myApp',[]);


function MyCtrl($scope, $window) {
    $scope.url = $window.location.href;
}

Displays...

{{url}}

5
  • attach controller to your angular module myApp Commented Jul 15, 2015 at 17:42
  • would work fine if you implemented angular properly and don't use angular version 1.01. What are you needing from url? Angular already has $location service and routers add more available data objects Commented Jul 15, 2015 at 17:43
  • 2
    also need to fix typo in location Commented Jul 15, 2015 at 17:54
  • @charlietfl Fixing the typo seemed to do the trick. I've edited the link. Thanks Commented Jul 15, 2015 at 18:00
  • jsfiddle.net/fhfepbtu/3 Commented Jul 15, 2015 at 18:13

2 Answers 2

1

You have a simple lexical error:

$scope.url = $window.locaton.href;

You put locaton instead location.

Sign up to request clarification or add additional context in comments.

Comments

1

See documentation and examples here from angular. angularjs.org $location

First implement your controller properly then you need to use the $location service like the following

myApp.controller("MyCtrl" ,["$scope","$window","$location", function($scope, $window, $location){
// Your controller code here..... 
$scope.url = $location.absUrl();
}]);

You can use $location.path(); to just get the last part of url or $location.absUrl(); to get the whole thing. Please read the linked documentation.

I edited the jsfiddle here https://jsfiddle.net/hth8sm5y/3/

EDIT: As others have said there was also a typo in your code "location" so fixing the typo fixes your code using $window. I'm not sure what your usage is but I suggested $location because it allows quick access to certain parts on the url like path() and hash() and also provides both getter/setter.

1 Comment

thanks for responding. I have tried using $location.path(). I couldn't get this.urlSnippet to display. And when I typed this.urlSnippet into the chrome console it says 'undefined'. Can your suggested answer be implemented in jsfiddle so I can see the full solution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.