1

ディレクティブで新しいプロパティが設定された後、モデルが完全に上書きされないという奇妙な問題が発生しています。

HTML:

<div ng-app="app">
    <div ng-controller="Dashboard">
        <div ng-repeat="item in items" my-dir items="items"></div>
        <button ng-click="replaceItems()">Replace</button>
    </div>
</div>

JS:

angular.module('app', []).controller('Dashboard', function($scope) {

    $scope.items = [{foo: "bar"}];

    console.log($scope.items);

    $scope.replaceItems = function () {
        $scope.items = [{}];

        console.log($scope.items);

    }

}).directive('myDir', function($injector) {
    return {
        scope: {
            items: '='
        },
        link: function(scope) {
            scope.items.newThing = 'I am new';
        }
    };
});

http://jsfiddle.net/Tgzdt/

[置換] をクリックして、コンソールを確認してください。

$scope.items が空の配列とオブジェクトで上書きされているにもかかわらず、newThing が残っているのはなぜですか?

4

3 に答える 3

1

をリセットしたい場合は、次のitemsように記述します。

$scope.items = [];

あなたの場合、空のオブジェクトを作成する{}ため、ディレクティブも呼び出します。

そのため、ディレクティブはnewThing = 'I am new';空のオブジェクトに追加されます。

で動作させたい場合は$scope.items = [{}]、次のようなディレクティブを記述します。

.directive('myDir', function($injector) {
    return {
        scope: {
            items: '='
        },
        link: function(scope) {            
            if(scope.items[0].foo !== undefined){  // dummy validation
                 scope.items.newThing = 'I am new';
            }            
        }
    };
}); 

デモFiddle

于 2013-11-14T13:14:06.477 に答える
1

変更するitemsと、ディレクティブが再び起動されます。

console.log をディレクティブに入れると表示されます。

于 2013-11-14T13:16:00.720 に答える
0

この線

scope.items.newThing = 'I am new';

$scope.items オブジェクトに新しいプロパティ「newThing」を追加するだけで、上書きしません。Chrome コンソールでオブジェクトを展開すると、次のように表示されます。

Array[1] 
0: Object 
    $$hashKey: "004" 
    foo: "bar"
    __proto__: Object 
length: 1 
newThing: "I am new"
__proto__: Array[0]
于 2013-11-14T13:16:12.627 に答える