passing paths in an angularjs directive

徘徊边缘 提交于 2019-12-13 04:30:16

问题


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'">



来源:https://stackoverflow.com/questions/17200244/passing-paths-in-an-angularjs-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!