سؤال

I tried to write a directive making an arbitrary element work like a link. Something like

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

to be translated into something like

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

or whatever will work. As a bonus I'd like the link to work, even when the current URL is already .../#overview.1

This sound pretty trivial, but I'm stuck with something like

.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>";
        }
    };
})

I'm perfectly sure, I'm doing it all wrong. I'm nearly sure it's all unnecessary complicated. However, I'm hoping to be able to learn something from the answers.


1I found myself repeatedly clicking on such a link in order to get to the "pristine overview state" and wondering that nothing happens. Obviously, the browser ignores links to the current location, but there could be a way around this?

هل كانت مفيدة؟

المحلول 2

Take a look at this example:

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
  };
});

You can play with it here (plnkr)

نصائح أخرى

You can add click event to directive dynamically.

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();
       });
     }
   }
 });

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top