Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Directive - Passing strings without having to use quotes

Here's a directive I created:

HTML:

<p-test something="'bla'"></p-test>

JavaScript:

.directive('pTest', function() {
    return {
        scope: {
            something: '=?'
        },
        templateUrl: 'components/testTemplate.html',
        controller: 'testController'
    };
});

I'd like to be able to pass 'bla' as a string without the '', in the following way:

<p-test something="bla"></p-test>

I know it's possible via the attributes parameter in link, but it's irrelevant in this case (correct me if I'm wrong) as I'm passing these parameters directly to scope.

like image 801
Maxim Laco Avatar asked Jan 03 '15 19:01

Maxim Laco


People also ask

What is restrict option in directive?

Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name. 'E' - only matches element name.

What is attrs in AngularJS?

Using attrs you are able to access the attributes defined in your html tag like <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> So in this case you will have access to the symbol and readonly attributes.

How to write directives in AngularJS?

Create New Directives In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the . directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive.


1 Answers

I'd like to be able to pass 'bla' as a string without the '', in the following way:

You would just need text binding (@) binding for that, instead of 2 way binding.

.directive('pTest', function() {
    return {
        scope: {
            something: '@?' //<-- Here
        },
        templateUrl: 'components/testTemplate.html',
        controller: 'testController'
    };
});

and with the text binding if you want to bind scope properties then use interpolation. i.e example if bla is a scope variable holding a string then just do:

 <p-test something="{{bla}}"></p-test>

Plnkr

like image 160
PSL Avatar answered Sep 24 '22 15:09

PSL