我有两个指令,我们称之为parent
和child
:
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
指令仍然显示属性feeding
为no
。为什么?我试过$rootScope.$apply()
但没有发生任何事情。
答案 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来触发摘要。