0

I have an angular controller and I want to conditionally set links depending on the result of a function

<a ng-href=" {{  setLink('contact') }}"

In the controller

angular.module("my-app")
    .controller('navController', ['$scope', '$document', function($scope, $document) {
    $scope.page = $document[0].title;
    $scope.home = "My app";

    $scope.setLink = function(path) {
        return $scope.page == $scope.home ? 'views/' + path : path;
    }
}]);

I can get it to work if I hardcore the urls like this

<a ng-href="{{ page == home ? 'views/contact.html' : 'contact.html' }}"

Does anyone know how to pass in a function to ng-href?

user5680735
  • 703
  • 2
  • 7
  • 21

2 Answers2

3

Your $scope.setLink function doesn't currently accept any parameters, so it isn't going to return the value that you're passing to it. Redefine the function to accept a parameter.

$scope.setLink = function(path) {
    return $scope.page == $scope.home ? 'views/' + path : path;
}

Edit following comment:

You're also missing the closing bracket on your <a> tag, which could be causing the issue. Not sure if this is a typo or an issue in the code. Change it to:

<a ng-href=" {{  setLink('contact') }}">Link Text<a/>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
jmknoll
  • 1,046
  • 5
  • 11
  • 30
1

this is how it should work

angular.module("myApp", [])
.controller('mController', ['$scope', '$document', function($scope, $document) {
    $scope.page = $document[0].title;
    $scope.home = "My app";
    $scope.setLink = function(path) {
      url = $scope.page == $scope.home ? 'views/' + path : path;
      return url;
    };
  }]);
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    
<div ng-app="myApp" ng-controller="mController">
  <a ng-href="{{setLink('contact')}}">{{setLink('contact')}}</a>
</div>
Shankar Gurav
  • 1,057
  • 9
  • 17