Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS pass URL in attribute to isolated scope of directive - unexpected token ':'

I'm fairly new to AngularJS and just started using it a few days ago, so forgive me if the question itself is incorrect.

The problem I ran into is that I'd like to pass a URL parameter via attribute to the isolated scope of my directive, but at the : part in http:// it gives me an error, saying Syntax Error: Token ':' is an unexpected token at column 5 of the expression [http://...

The HTML part of the directive (where I "call" it) is something like this:

<myDirective datasource="http://url"></myDirective>

And I bind(?) it to the isolated scope like this:

scope: {
    dataSource: '=datasource'
}

If the value of the attribute contains only simple characters, it works. How can I solve this?

Thanks.

like image 960
Martin Fejes Avatar asked Feb 07 '15 20:02

Martin Fejes


People also ask

How to isolate the scope of a directive in AngularJS?

In AngularJS, directives have direct access to its parent by default. Therefore, we can only use it once within a given scope. If you want to make it reusable then we have to isolate it from the parent scope. We can use a directive’s scope property to isolate the scope.

How to access scope variables from the templateurlfunction in AngularJS?

AngularJS will call the templateUrlfunction with two parameters: the element that the directive was called on, and an attrobject associated with that element. Note:You do not currently have the ability to access scope variables from the templateUrlfunction, since the template is requested before the scope is initialized.

What happens when an AngularJS scope is destroyed?

Similarly, when an AngularJS scope is destroyed, it broadcasts a $destroyevent to listening scopes. By listening to this event, you can remove event listeners that might cause memory leaks.

What is the use of prefixes in AngularJS?

AngularJS covers that too, by allowing communication between the parent scope and the directive. The directive can gain access to the parent scope by using some special symbols known as prefixes. Isolated scope - Prefixes In the case of an isolated scope, the directive scope is completely unaware of its parent’s scope.


2 Answers

In your case angular is trying to evaluating value of datasource attribute. Because you mention = i.e. two way binding for variable.

If you wrap URL inside ' (single quote) will solve your problem. because the mentioned value will directly binded to directive isolated scope variable.

Markup

<my-directive datasource="'http://url'"></my-directive>
like image 109
Pankaj Parkar Avatar answered Sep 19 '22 05:09

Pankaj Parkar


Dont use '=' in directive instead use @ because you are passing normal string.

scope: {
    dataSource: '@datasource'
}
like image 24
squiroid Avatar answered Sep 22 '22 05:09

squiroid