AngularJS指令更新父对象的对象属性

时间:2014-10-31 16:33:47

标签: javascript angularjs angularjs-directive angularjs-scope

我正在构建一个应该更新其父级范围的指令。基本上这就是我想要的:

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

该指令应该设置传递给属性的模型&#34; foo&#34;到&#34; bar&#34;。所以父母的范围应该是这样的:

$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/

1 个答案:

答案 0 :(得分:2)

您需要对foo属性使用双向绑定,方法是使用&#39; =&#39;

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

查看更新的fiddle