Jared Whipple
Jared Whipple

Reputation: 1171

How do I pass value directly into a directive?

I have a simple angular directive I would like to pass value to.

 <div my-component binding-foo="foo">
    <strong>get:</strong> {{isolatedBindingFoo}} // get it to output foo?
</div>

Upvotes: 1

Views: 125

Answers (2)

hazzik
hazzik

Reputation: 13344

AngularJS mangles HTML attributes to JS properties. eg, binding-foo in HTML will be mangled to bindingFoo in JS, and vice-versa

var myModule = angular.module('myModule', [])
.controller('yourController', ['$scope', function($scope) {

    $scope.isolatedBindingFoo = '';

}])
.directive('myComponent', function() {
    return {
        restrict:'E,A',
        controller: 'yourController',
        scope: true, 
        link: function($scope, $element, attrs) {
            $scope.isolatedBindingFoo = attrs['bindingFoo'];
        } 
    } 
});

http://jsfiddle.net/b2xo0o5u/3/

But in the example case this should be enough:

angular.module('myModule', [])
.directive('myComponent', function() {
    return {
        restrict:'EA',
        scope: {
            'isolatedBindingFoo': '@bindingFoo'
        }
    } 
});

http://jsfiddle.net/b2xo0o5u/4/

Upvotes: 0

Danny Bullis
Danny Bullis

Reputation: 3199

HTML

<div my-component binding='foo'> ... </div>

JS

yourApp.controller('yourController', ['$scope', function($scope) {

    $scope.isolatedBindingFoo = '';

}])
.directive('myComponent', function() {
    return {
        controller: 'yourController',
        scope: {
            'binding': '=binding'
        }, 
        link: function($scope, $element, attrs) {
            $scope.isolatedBindingFoo = attrs['binding'];
        } 
    } 
});

http://fdietz.github.io/recipes-with-angular-js/directives/passing-configuration-params-using-html-attributes.html

Cheers

Upvotes: 1

Related Questions