Gabin
Gabin

Reputation: 1288

AngularJS directive updating property of object on parent's scope

I am building a directive that is supposed to update its parent's scope. Basically this is what I want:

<div foo="foo.foo"></div>

This directive is supposed to set the model passed to the attribute "foo" to "bar". So the parent's scope is supposed to have something like:

$scope.foo = { foo: 'foo' };

HTML:

<div ng-app="app">
    <div ng-controller="fooController">
        {{ foo.foo }}
        <div foo="foo.foo"></div>
    </div>
</div>

JS:

var app = angular.module( 'app', [] );

app.directive( 'foo', function () {
    return {
        restrict: 'A',
        link: function ( scope, attrs ) {
            scope[ attrs.foo ] = 'bar';
        }
    };
} );

app.controller( 'fooController', [ '$scope', function ( $scope ) {
    $scope.foo = {
        foo: 'foo'
    };
} ] );

JSFiddle: http://jsfiddle.net/wphvc75k/

Upvotes: 0

Views: 603

Answers (1)

Simon H
Simon H

Reputation: 21005

You need to use a 2-way binding for foo attributee, by using the '='

app.directive( 'foo', function () {
    return {
        scope : {
            foo: '='
        },
        restrict: 'A',
        link: function ( scope, attrs ) {
            console.log( scope );
            console.log( scope[ attrs.foo ] );
            scope.foo = 'bar';
        }
    };
} );

See updated fiddle

Upvotes: 2

Related Questions