为什么父模型不会在 Angular 指令函数调用时得到更新?

Why won't parent model get updated on Angular Directive function call?

http://jsfiddle.net/2dgzt18a/

我希望在输入中按下 Enter 时父项上的模型得到更新。但事实并非如此。控制台日志的输出看起来很有希望,就像它应该做的那样。我需要使用 $watch 吗?对此表示怀疑,但我想我会问。

HTML

<div data-ng-app="testApp">
    <div data-ng-controller="testCtrl">
        <strong>{{pkey}}</strong>
        <span data-test-directive 
              data-parent-item="pkey" 
              data-parent-update="update(pkey)"></span>
    </div>
</div>

指令

var testApp = angular.module('testApp', []);

testApp.directive('testDirective', function ($timeout) {
    return {
        scope: {
            key: '=parentItem',
            parentUpdate: '&'
        },
        replace: true,
        template: '<div><input type="text"></input></div>',
        link: function(scope, elem, attrs) {
           elem.bind('keydown keypress', function(event) {
              if (event.which === 13) {
                  scope.parentUpdate({ pkey: 'D+' + scope.key});
                  event.preventDefault();
              }
           })
        }
    };
});

控制器

testApp.controller('testCtrl', function ($scope) {
    $scope.pkey = 'golden';
    $scope.update = function (k) {
        // Expecting local variable k, or $scope.pkey to have been
        // updated by calls in the directive's scope.
        console.log('CTRL:', $scope.pkey, k);
        $scope.pkey = 'C+' + k;
        console.log('CTRL:', $scope.pkey);
    };
});

我相信我已经看到在指令中使用控制器的这项工作,但由于我对按键事件感兴趣,所以我需要使用 link。

elem.bind只是将js函数绑定到事件上,没有别的。

添加scope.$apply().

P.S。即 ng-click 的作用几乎相同:绑定事件并在回调后调用应用。

P.S.1。如果你可以使用更现代的 angular 版本 - 有 ng-keypress 和类似的指令。

scope.$apply 不推荐使用。最好使用 $timeout

The $timeout does not generate error like „$digest already in progress“ because $timeout tells Angular that after the current cycle, there is a timeout waiting and this way it ensures that there will not any collisions between digest cycles and thus output of $timeout will execute on a new $digest cycle