AngularJS - 根据当前路径更改href属性

时间:2017-03-20 09:18:48

标签: javascript angularjs twitter-bootstrap angularjs-scope angularjs-ng-href

如何根据当前路径更改href-Attribute的值?

AngularJS中的我的if子句如下所示:

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

我的HTML看起来像这样:

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

3 个答案:

答案 0 :(得分:4)

您可以使用ng-href动态为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
}

答案 1 :(得分:1)

您可以使用

获取当前路径
var url = $location.absUrl().split('?')[0];

替换href属性

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

答案 2 :(得分:0)

 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>