passing paths in an angularjs directive

2019-09-04 12:09发布

问题:

I have a directive which i'd like to pass a path

<mydirective api="/my/tomcat/server?asd=123&efg=456">

However I get "Lexer Error: Unexpected next character". I assume some encoding needs to take place. Can someone advice?

回答1:

I'm not sure why you are getting the lexer error without seeing your code, if you could update the post, we may be able to tell why that happens. In the meantime, there are a few ways to retrieve an attribute value in your directive. Not all will work with a string literal.

1) The @ isolate scope binding: This parses the value and will work as is with your HTML. The parse actually happens later so this value will not be immediately available in the directive's internal methods (i.e. link, etc.) and is best used in the directive's template method. Ex.:

scope: {
    api: '@'
}

2) The = isolate scope binding: This will work if you wrap your expression in single quotes because it evaluates the attribute as an expression. Ex.:

scope: {
    api: '='
}

And in your HTML (notice the single quotes):

<mydirective api="'/my/tomcat/server?asd=123&efg=456'">

3) Attribute Evaluation: This allows you to evaluate the attribute string value directly from the directive's internal methods and will work as is with your HTML. Ex:

link: function(scope,element,attrs){
    console.log(attrs.api);
}

You can read more about directives in the AngularJS directive doc here.



回答2:

Angular try to evaluate the expression in the api attribute, you have to surround it with quotes :

<mydirective api="'/my/tomcat/server?asd=123&efg=456'">