简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM