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.