指令,使任何元素都像链接一样工作



我试着写一个指令,使任意元素像链接一样工作。就像

<span goto="overview">Overview</span>

被翻译成

<span ng-click="$location.path('#/overview')">Overview</span>

之类的。作为奖励,我希望链接工作,即使当前的URL已经是.../#overview1

这听起来很琐碎,但我还是要用

这样的东西。
.directive('goto', function($location) {
    return {
        template: function(element, attrs) {
            // Here `attrs` should be used but how?
            var ref = "#/" + element.attr('goto');
            // This is a mystery to me.
            // I guess, transclusion is the way to go, but how exactly?
            var elementContent = getEverythingBelowElementButHow();
            // I doubt `$location` will be visible on the invocation site.
            return "<span ng-click='$location.path(" +
                ref + "'>" +
                elementContent +
                "</span>";
        }
    };
})

我非常肯定,我做错了。我几乎可以肯定,这一切都是不必要的复杂。然而,我希望能从这些答案中学到一些东西。


1我发现自己反复点击这样的链接,以便进入"原始概述状态",并想知道什么也没有发生。显然,浏览器会忽略指向当前位置的链接,但是否有办法解决这个问题?

你可以动态地添加click事件到指令中。

angular.module('ExApp')
 .directive('goto', function($location) {
   return {
     restrict: 'A',
     scope: {
       //scope variables            
     },
     link: function(scope, element, attr) {
       element.on('click', function() {
         $location.path('/overview');
         scope.$apply();
       });
     }
   }
 });

活塞:http://plnkr.co/edit/n6VbZnAVzM4y0p8dbmvf?p=preview

看一下这个例子:

app.directive('goto', function($location){
  function link(scope, element, attr){
    scope.gotoLink = function(){
      alert(scope.goto);
      //$location.path(scope.goto);
    };
  }
  return {
    restrict: 'A',
    transclude: true,
    scope:{ goto: '@' },
    template: '<span ng-click="gotoLink()"><span ng-transclude></span></span>',
    link: link
  };
});

你可以在这里玩(plnkr)

最新更新