AngularJS - Parent无法修改从child推送到其范围的条目

时间:2014-07-19 00:36:49

标签: angularjs

我有两个指令,我们称之为parentchild

app.directive('parent', function() 
{
    return {
        restrict: 'C',
        link: function(scope, element, attrs)
        {
            scope.baby = [];
            scope.isHome = false;
        }, 
        controller: function($scope)
        {
            Keypress.on('shift && n', function() 
            {
                if ($scope.isHome)
                {
                    console.log('Baby is Home. Feed him.');
                    $scope.baby.feeding = 'yes';
                }
                console.log($scope.baby);
            });
        }
    }   
});

app.directive('child', function() 
{
    return {
        restrict: 'C',
        controller: function($scope)
        {
            $scope.takeHome = function()
            {
                $scope.baby = {
                    name : 'My Baby',
                    feeding : 'no'
                }
                $scope.isHome = true;
            }
        }
    }   
});

使用非常简单的HTML:

<div class="parent">
    <div class="child">
        <button ng-click="takeHome">Take Baby Home</button>
        <span ng-if="isHome">Baby is fed? {{ baby.feeding }}</span>
    </div>
</div>

这里,Keypress是一个在应用参数时调用回调的库。当我按下“Take Baby Home”按钮,然后按“shift”和“n”时,控制台会记录以下内容:

Baby is Home. Feed him.
{name : 'My Baby', feeding: 'yes'}

child指令仍然显示属性feedingno。为什么?我试过$rootScope.$apply()但没有发生任何事情。

1 个答案:

答案 0 :(得分:0)

尝试:

Keypress.on('shift && n', function() 
{
    if ($scope.isHome)
    {
        console.log('Baby is Home. Feed him.');
        $scope.$apply(function() {
             $scope.baby.feeding = 'yes'; 
        });
    }
    console.log($scope.baby);
});

Angular不了解Keypress,因此需要调用$ apply来触发摘要。