7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Passing argument into Angular Controller via HTML data attributes

Last updated at Posted at 2014-04-02

Just learned a proper way to pass arguments via data attribute. It's very easy but I didn't found this on Google / StackOverflow.

Here is the scenario:

  • There are some variables generated from server-side.
  • They have to be sent into an Angular Controller as a model.

Some StackOverflow answers say that you have to embed JavaScript literals into the code of Angular Controllers, which makes it hard to extract controllers to standalone JavaScript files. Others say that you can assign variables via ng-init expressions, which I don't like because eval is evil.

I think it's better to pass variables via data- attribute, but I didn't know how to do until I found there are some hidden providers in Controller.

Use $attrs

It's simple and clean. You can pass variables via data-something="123".

<div ng-app="MyApp">
  <div ng-controller="MyController" data-something="hello">
    {{ modifiedSomething }}
  </div>
</div>
var app = angular.module('MyApp', []);

app.controller('MyCtrl', [
  '$scope', '$attrs',
  function($scope, $attrs) {
    $scope.modifiedSomething = $attrs.something + " world";
  }
]);

You can see demo here: http://plnkr.co/edit/njwpOFYYgs90XXumUMBX

Besides $attrs, there is also an $element provider for you to access the element of the controller.

Missing Document :(

However, I didn't find these providers on the official API reference of Angular.js. Yes I did searched attrs and element but nothing was found.

It seems that the document of Angular.js is still not good enough.

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?