简体   繁体   English

角度-通过功能有条件设置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? 有人知道如何将函数传递给ng-href吗?

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. $ scope.setLink函数当前不接受任何参数,因此不会返回您要传递给它的值。 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. 您还缺少<a>标记的右括号,这可能是导致问题的原因。 Not sure if this is a typo or an issue in the code. 不确定这是拼写错误还是代码中的问题。 Change it to: 更改为:

<a ng-href=" {{  setLink('contact') }}">Link Text<a/>

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM