Reputation: 39
I have a function that generates a URL. I want to use it inside of ng-href
. This is all fine, until I had to move the method outside of $scope
. That doesn't work any more.
See this plunker example:
EDIT New Plunker example with comments:
https://plnkr.co/edit/z4txeXD1J2PJCfcBNw5C?p=preview
Old link: https://plnkr.co/edit/qb9w6A5nCNet2MCynnGH?p=preview
I can get it to work with some hacks, such as putting the method in the root scope (as in the example), but that's really unwieldy. Is there a better way to "import" methods into scope?
Upvotes: 0
Views: 729
Reputation: 1
Why not just pass in the $window for the variables you need from outside, and instead just use $scope as you would normally in angular inside the ng-href? ng="{}" using the single curly braces in angular refers to expresssions.
<a ng-href="query">$scope.query</a>
</div>
<script>
function getUrlGlobalScope(q) {
return 'some_url_global?q=' + q;
}
(function(angular) {
'use strict';
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.getUrlRootScope = getUrlGlobalScope;
})
.controller('MyController', ['$scope','$window', function($scope,$window) {
$scope.getUrlInScope = function(q) { return 'some_url?q=' + q; }
$scope.query = 'query';
Upvotes: 0
Reputation: 732
You could create a directive
that does the URL generation and creates a ng-href
(or even creates an anchor <a>
)
Upvotes: 1