Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular JS, how do I inject data from directive attribute to template?

Here's my directive:

app.directive("helloWorld", function() {
  return {
    restrict: "E",
    scope: {
      name: "bind"
    },
    template: "<div>a {{name}} a</div>"
  };
});

Here's how I use it:

<hello-world name="John Smith"></hello-world>

I expect this page to be like this, when I run it:

<hello-world>
  <div>a John Smith a</div>
</hello-world>

But for some reason, name is not injected and actual result is like this:

<hello-world>
  <div>a {{name}} a</div>
</hello-world>

Anything I'm missing? I'm using Angular JS 1.0.2

like image 458
Andrey Agibalov Avatar asked Oct 14 '12 10:10

Andrey Agibalov


People also ask

How do I invoke a directive in AngularJS?

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.

Does directive have template?

Components are directives with templates. The only difference between Components and the other two types of directives is the Template. Attribute and Structural Directives don't have Templates.

Which directive can have a template in Angular?

Angular creates the directive class and specifies the CSS selector, appUnless , that identifies the directive in a template. Import Input , TemplateRef , and ViewContainerRef . Inject TemplateRef and ViewContainerRef in the directive constructor as private variables.

What is injector in AngularJS?

Overview. $injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.


1 Answers

The scope declaration is strange. I'm not sure about the "bind" declaration - maybe its something from the previous versions.

The current syntax for binding to a directive's attribute is like this:

return {
    restrict: "E",
    scope: {
      name: "@name"
    },
    template: "<div>a {{name}} a</div>"
};

In general, @attributeName. See here for more information on directives.

like image 158
Jakub Wasilewski Avatar answered Oct 26 '22 05:10

Jakub Wasilewski