更清洁的方式在ng-repeat上提供不同的href URL?

时间:2014-04-02 01:41:13

标签: javascript html angularjs angularjs-ng-repeat ng-repeat

我使用hide和show在ng-repeat上显示不同的href链接,具体取决于routeParams上是否存在userid。 href标记内的图像对于两种条件都是相同的。

例如:

<div ng-repeat="trip in trips">
    // If userid exists, the user is authenticated so provide userid on url
    <a ng-show="userid" ng-href="#/trip/{{trip.tripid}}/user/{{userid}}">
        // Same exact image as in ng-hide
        <img ng-src="trip.jpg" width="200" height="200" alt="Trip Photo">
    </a>
   // If userid does not exist, the user is not authenticated so no userid on url
    <a ng-hide="userid" ng-href="#/trip/{{trip.tripid}}/">
        // Same exact image as in ng-show
        <img ng-src="trip.jpg" width="200" height="200" alt="Trip Photo">
    </a>
</div>

我觉得有一种不那么冗余的方法可以避免使用ng-show和ng-hide来改变URL并在锚标记内写入重复的图像标记。

1 个答案:

答案 0 :(得分:0)

您可以使用过滤器并传递数据:

filter('urlFormatter', function() {
    return function(tripid, userId) {
        if(angular.isDefined(userId)) {
            return "#/trip/"+tripid+"/user/"+userId;
        }
        return "#/trip/"+tripid+"/";
    }
});

然后在您的属性中使用它:

ng-href="trip.tripid | urlFormatter:userid"

或者

ng-href="trip.tripid | urlFormatter"

您还可以使用$ location服务并更改路径:

$location.path('/path/foo/bar')

使用此方法,您可以将ng-click绑定到标记并在控制器中应用位置逻辑,即,如果传递了用户标识。

一个例子:

<a ng-click="goSomewhere(trip.tripid, userid)">

控制器将在哪里

controller('demoCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.goSomewhere = function(tripid, userid) {
        if(angular.isDefined(userid) {
            $location.path("/trip/"+tripid+"/user/"+userid);
        }
        else {
            $location.path("/trip/"+tripid+"/");
        } 
    }
}]);