AngularJS - change href Attribute based on current path

和自甴很熟 提交于 2019-12-12 02:07:41

问题


How can I change the value of the href-Attribute based on the current path?

My if clause in AngularJS looks like this:

    if (newPath.indexOf('test') > -1) {
      // change the value of the href-Attribute
    } else {
      // don't change the value of the href-Attribute
    }

My HTML looks like this:

    <li>
      <a aria-expanded="false" role="button" href="/path1/path2/path4">Downloads</a>
    </li>

回答1:


you can use ng-href to dynamically assign value to href

<li>
  <a aria-expanded="false" role="button" ng-href="{{myVar}}">Downloads</a>
</li>

$scope.myVar ="/path1/path2/path4";

if (newPath.indexOf('test') > -1) {
      $scope.myVar = "/path1/path2/path4" // you can assign whatever path to this variable 
} else {
      $scope.myVar = "/path1/path2/path3" // you can assign whatever path to this variable
}



回答2:


You can get current path with

var url = $location.absUrl().split('?')[0];

Replace href attribute

var myEl = angular.element( document.querySelector( '#selector' ) );
myEl.attr('href',url);



回答3:


 if (newPath.indexOf('test') > -1) {
      $scope.newPath = newPath.test;
    } else {
      // don't change the value of the href-Attribute
    }

<li>
      <a aria-expanded="false" role="button" ng-href="{{newPath}}">Downloads</a>
    </li>


来源:https://stackoverflow.com/questions/42899708/angularjs-change-href-attribute-based-on-current-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!