如何通知我 angular 通过 ng-model 设置输入字段的值?

How can I be notified of angular setting the value of an input field via ng-model?

this fiddle

我有一个简单的指令,我只记录它添加到的复选框的值:

myApp.directive('myCheckBox', function () {
    return function (scope, element, attrs) {
        console.log('directive linking function, checked = ', element[0].checked);

        // not triggered on startup
        element.bind('change', function (event) {
            console.log('onChange, checked = ', element[0].checked);
        });

    }
});

此复选框的值绑定到封闭控制器中的 属性:

<div ng-app="myApp">
    <div ng-controller="myController">Boolean1:
        <input my-check-box type="checkbox" ng-model="settings.boolean1" />
    </div>
</div>

像这样:

myApp.controller('myController', ['$scope', function ($scope) {
    $scope.settings = {
        boolean1: true
    }
}]);

问题是我无法找到一种方法来找出(在指令中)"initial" 值(即控制器设置的值)是什么。

如果您查看控制台,您会看到初始日志语句将其报告为 false(我不确定为什么,但我猜这是在 Angular 的数据绑定之前执行的地方 - 有没有更好的方法来设计这个,所以情况并非如此?)。如果您手动切换值,则会触发更改事件。但是它并没有在启动时触发,所以我不知道如何获取该值。

我如何在启动时简单地获取值(通过 ng-model 设置),或者我如何监听该变化?

您需要做的是 $watch 附加到元素的 ngModel。当你观察一个变量时,你可以看到旧值和新值。

myApp.directive('myCheckBox', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            console.log('directive linking function, checked = ', element[0].checked);

            scope.$watch(function () {
                return ngModel.$modelValue;
            }, function (newValue, oldValue) {
                console.log(newValue, oldValue);
            });
        }
    };
});

JSFFIDLE