Reputation: 74018
Angular documentation advises to use Angular services Angular expressions:
Instead use services like $window and $location in functions called from expressions. Such services provide mockable access to globals.
– https://docs.angularjs.org/guide/expression#context
However, these services do not appear to be in the view scope by default, e.g.
{{$location || 'Undefined'}}
Will produce "Undefined".
If I want to access $location
service from a view, do I need to inject it to the scope?
/* some controller */ function ($scope, $location) {
$scope.$location = $location;
}
Upvotes: 4
Views: 1538
Reputation: 2394
The best thing to do here is to encapsulate what you are trying to do within either a controller method call, or a directive. So for example, if you wanted to bring the current URL through to the view, you should probably do something like the following.
VIEW
<p>{{ CurrentUrl }}</p>
CONTROLLER
(function(app){
app.controller("myController",["$scope","$location",function($scope,$location){
$scope.CurrentUrl = $location.$$path; // or whatever is most useful to display
}]);
})(myApp);
This means that you are following the IOC pattern of Angular, and not tightly coupling "$location" to either your view or your controller.
Using "$location" here is obviously just an example. You could use "$window" or whatever you wanted.
Upvotes: 1