Search code examples
angularjsangular-directive

angularJS directive for href behavior


I am trying to get a href behavior added to tag. How can this be done? Is there way in angular directives to add same behavior to other html tags.

I have added

  <div click-element="#/page1/test?Tab=1/">

but i get the following lexer error for passing the URL as parameter:

 "stack": "Error: [$parse:lexerr] Lexer Error: Unexpected next character  at columns 0-0 [#] in expression [#/page1/test?Tab=1/].

How can i pass the URL as attribute parameter?

Updated

I want the click-element directive to be the one which handles navigation. The element would rather look like:

<div click-element="#/page1/test?Tab=1/">

In click-element directive:

 function clickElement( $location) {

            var clickElementDefinition = {
                restrict: 'A',
                scope: {
                    clickElement: "="
                },
                link: clickElementMethod
            };
            return clickElementDefinition ;

            function clickElementMethod(scope, element, attrs) {
                element.bind('click', function (event) {
                        if (scope.clickElement) {
                        var arr = scope.clickElement.split("?");
                        var queryParam = arr[1].split("=") || "";
                        $location.path(arr[0]).search(queryParam[0], queryParam[1]);
                    }
                });
            }
        };

I still get the lexer error on directive load.


Solution

  • You need to either add a second set of quotes to the click-element or use attrs.clickElement instead of scope.

    <div click-element="'#/page1/test?Tab=1/'">
    

    or

    function clickElementMethod(scope, element, attrs) {
                element.bind('click', function (event) {
                        if (attrs.clickElement) {
                        var arr = attrs.clickElement.split("?");
                        var queryParam = arr[1].split("=") || "";
                        $location.path(arr[0]).search(queryParam[0], queryParam[1]);
                    }
                });
            }
    

    or

    scope: {
         clickElement: "@"
    },