2014-03-27 13 views
3

在我的應用中,我有兩種類型的組織配置文件。當用戶點擊配置文件名稱時,首先需要檢查我是否擁有該組織的高級配置文件,如果是,請按照該方向路由用戶。如果沒有高級配置文件,則將用戶發送到標準配置文件。AngularJS - 在通過控制器進行有條件路由時,在新選項卡中打開鏈接

我正在使用ng-click這樣做,它將ID和資源(在本例中爲組織)參數發送到控制器,在該控制器中評估條件,然後用戶按正確方向路由。當用戶點擊正常時,所有這些都可以正常工作。

但是,當用戶嘗試在新選項卡中打開鏈接時,通過右鍵單擊並選擇該選項,新選項卡將打開並顯示當前頁面的網址。因此,ng-click和控制器在打開新選項卡之前未觸發或評估請求。

如何通過代碼進行更改,以便Angular在打開新選項卡之前處理ng-click請求?或者更廣泛地說,我如何允許我的用戶在新標籤中打開這些鏈接中的一個,以便它們不僅僅顯示它們當前所在的頁面?

HTML

<div ng-controller="ProfileRouter"> 
     <div ng-repeat="org in orgs | orderBy:'org.name'"> 
      <a href="" ng-click="profileCheck('{{ org.id }}', 'organisation')">{{ org.name }}</a> 
     </div> 
</div> 

內ProfileRouter控制器

$scope.profileCheck = function (id, resource) { 

    $http({method: 'GET', url:'/IdCheck', params:{'id': id}) 
    .success(function(data) { 

     var count = data.hits.found; 
     if (count) { 
      var hash = data.hits.hit[0].id; 
     } 

     if (resource == 'organisation') { 
      theResource = 'universities'; 
      page = 'overview'; 
     } 

     if (count == 1) { 
      window.location.href = "/" + theResource + "/profile/" + hash + "/" + page; 
     } 
     if (count == 0) { 
      window.location.href = "/" + resource + "/" + id; 
     } 

    }) 
    .error(function(data) { 
     $scope.data = data || "Can't get resource"; 
    }); 
} 

回答

3

我知道這是一個老問題。但我發現這個&的解決方案發布它可能會幫助其他人。

首先,我已經創造了右鍵單擊自定義指令:

module.directive('tabRightClick',['$parse', function($parse) { 
    return function(scope, element, attrs) { 
     var fn = $parse(attrs.tabRightClick); 
     element.bind('contextmenu', function(event) { 
      scope.$apply(function() { 
    //   event.preventDefault(); 
       fn(scope, {$event:event}); 
      }); 
     }); 
    }; 
}]); 

然後應用這個指令,因爲在HTML文件中的屬性和調用被稱爲上ng-click同樣的方法:

<div ng-controller="ProfileRouter"> 
     <div ng-repeat="org in orgs | orderBy:'org.name'"> 
      <a href="{{locationPath}}" ng-click="profileCheck('{{ org.id }}', 'organisation')" tab-right-click= "profileCheck('{{ org.id }}', 'organisation')">{{ org.name }}</a> 
     </div> 
</div> 

這裏locationPath是一個$scope綁定變量,我們需要在控制器中實現。 它的值應該根據各種條件在profileCheck函數中更新。

$scope.profileCheck = function (id, resource) { 

    $http({method: 'GET', url:'/IdCheck', params:{'id': id}) 
    .success(function(data) { 

     var count = data.hits.found; 
     if (count) { 
      var hash = data.hits.hit[0].id; 
     } 

     if (resource == 'organisation') { 
      theResource = 'universities'; 
      page = 'overview'; 
     } 

     if (count == 1) { 
      window.location.href = "/" + theResource + "/profile/" + hash + "/" + page; 
      $scope.locationPath = "/" + theResource + "/profile/" + hash + "/" + page; 
     } 
     if (count == 0) { 
      window.location.href = "/" + resource + "/" + id; 
      $scope.locationPath = "/" + resource + "/" + id; 
     } 

    }) 
    .error(function(data) { 
     $scope.data = data || "Can't get resource"; 
    }); 
} 

希望它有幫助。

相關問題