我已经用工作代码更新了你的小提琴。如果你在你的指令中需要 ngModel 并观察它的 $modelValue,你就能得到你正在寻找的行为。
HTML:
<div switch ng-model="testObject.switch">
指示:
booleanSwitchModule.directive('switch', [function () {
return {
scope: {},
require: "?^ngModel",
link: function (scope, elem, attr, ngModel) {
var timesChanged = 0;
scope.$watch(function() {return ngModel.$modelValue; }, function (val) {
if (val != undefined) {
alert("model changed " + ++timesChanged + " times");
scope.switchPosition = scope.model;
}
});
},
restrict: 'EA',
replace: true,
transclude: true,
template: '<label class="switch">' +
'directive scope model: {{ngModel}}' +
'<span ng-transclude></span>' +
'</label>',
}
}]);
这是更新的小提琴:https ://jsfiddle.net/62911kx5/3/