Search code examples
javascriptangularjsangularjs-ng-href

Angular - Conditionally setting ng-href through function


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?


Solution

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