u-sref on tr元素在新标签中打开

时间:2015-03-05 07:58:16

标签: javascript angularjs angular-ui-router

我有重复的表行和设置ui-sref属性。单击时,它们会导航到正确的位置。但是,它们不能⌘命令 -clicked(或在新选项卡中打开)。

我假设这是因为他们设置了href,当元素是锚标记(<a>)时,它会被尊重,但不会在其他元素上设置。

<tr ng-repeat="item in items" ui-sref="view-item({itemId:item.id})">

快速修复的想法?

3 个答案:

答案 0 :(得分:4)

我能够通过ng-click功能实现我想要的目标。

app.run(function($rootScope, $state) {

    $rootScope.navigate = function($event, to, params) {

        // If the command key is down, open the URL in a new tab
        if ($event.metaKey) {
            var url = $state.href(to, params, {absolute: true});
            window.open(url,'_blank');

        } else {
            $state.go(to, params);
        }

    };

});

用法

<tr ng-repeat="item in items" ng-click="navigate($event, 'view-item',{itemId:item.id})">

答案 1 :(得分:0)

对于代码触发导航,我们应该使用$state.go(to, params, options)

$state.go(to, params, options)

  

转换到新状态的便捷方法。 $state.go在内部调用$state.transitionTo但会自动将选项设置为{ location: true, inherit: true, relative: $state.$current, notify: true }.这允许您轻松使用绝对或相对路径,并仅指定您要更新的参数(同时允许未指定的参数)继承自当前活跃的祖先州。)

PARAMS:

  

to string - 绝对州名或相对州路径。一些例子:

$state.go('contact.detail') - will go to the contact.detail state
$state.go('^') - will go to a parent state
$state.go('^.sibling') - will go to a sibling state
$state.go('.child.grandchild') - will go to grandchild state

...

此外,我们可以将其注入$rootScope,以便稍后可以使用 $state (或甚至$state.go() anyhwere

检查sample app.js代码:

.run(
    [ '$rootScope', '$state', '$stateParams',
    function ($rootScope, $state, $stateParams) {
    // It's very handy to add references to $state and $stateParams to the $rootScope
    // so that you can access them from any scope within your applications.For example,
    // <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
    // to active whenever 'contacts.list' or one of its decendents is active.
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

}])

答案 2 :(得分:0)

这是我基于DesignerGuy解决方案的解决方法。一个也支持CTRL +点击和中心按钮点击的指令。

    function navigate($state) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.on('mousedown', function(event) {
        event.preventDefault();
        var to = attrs.navigate.split("(")[0];
        var str = attrs.navigate.split("(")[1].slice(0, -1);
        var params = JSON.parse(JSON.stringify(eval('(' + str + ')')));
        if (event.metaKey || event.ctrlKey || event.which == 2) {
          var url = $state.href(to, params, {
            absolute: true
          });
          window.open(url, '_blank');

        } else if (event.which == 1) {
          $state.go(to, params);
        }
      });
    }
  }
}

angular
  .module('xxx')
.directive('navigate', navigate)

并且在视图中只是这个

<tr ng-repeat="item in items" navigate="view-item({itemId: {{item.id}} })">