Angular - Conditionally setting ng-href through function

1.1k Views Asked by At

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?

2

There are 2 best solutions below

0
Shankar Gurav On BEST ANSWER

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="[email protected]" 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>

2
jmknoll On

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/>