If you are using isolate scope, then you could use the two-way binding: "="
. This would take a model or a literal, in the following way (assuming $scope.model = "test"
:
<div foo="model"></div> <!-- test | string -->
<div foo="'text'"></div> <!-- text | string -->
<div foo="5"></div> <!-- 5 | number -->
<div foo="{a: 5}"></div> <!-- {"a":4} | object -->
and this is the directive definition:
app.directive("foo", function(){
return {
scope: {
foo: "="
},
template: "<span>{{foo}}</span> | <span>{{type}}</span>",
link: function(scope){
scope.type = typeof scope.foo;
}
}
})
plunker
EDIT:
As per feedback from @JoeEnzminger, the "="
is an expensive way to get the actual object as it sets up 2 watchers (for a two-way binding).
For one-way binding (with a single watcher)
You could the foo: "@"
binding. This will result in all of the values being interpreted as a string
. Specifically, to pass the value of $scope.model
you would need to use an expression: {{model}}
.
Alternatively, as suggested by @JoeEnzminger's answer below, you could use the foo: "&"
binding. This will allow to get the actual model/object back. The drawback is a more awkward function syntax {{foo()}}
for expressions.
For one-time binding:
If you could do away with one-time binding, then you could use the $parse
service to get the actual object.
For isolate scope:
scope: {},
link: function(scope, element, attrs){
scope.foo = $parse(attrs.foo)(scope.$parent);
}
For inherited scope:
scope: true,
link: function(scope, element, attrs){
scope.foo = $parse(attrs.foo)(scope);
}