我正在尝试编写一个使用隔离范围和 ngModel 指令的指令。
问题:
当模型在指令中更新时,调用者的值没有得到更新。
HTML:
<test-ng-model ng-model="model" name="myel"></test-ng-model>
指示:
app.directive(
'testNgModel', [
'$timeout',
'$log',
function ($timeout, $log) {
function link($scope, $element, attrs, ctrl) {
var counter1 = 0, counter2 = 0;
ctrl.$render = function () {
$element.find('.result').text(JSON.stringify(ctrl.$viewValue))
}
$element.find('.one').click(function () {
if ($scope.$$phase) return;
$scope.$apply(function () {
var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
form.counter1 = ++counter1;
ctrl.$setViewValue(form);
});
});
$element.find('.two').click(function () {
if ($scope.$$phase) return;
$scope.$apply(function () {
var form = angular.isObject(ctrl.$viewValue) ? ctrl.$viewValue : {};
form.counter2 = ++counter2;
ctrl.$setViewValue(form);
});
});
$scope.$watch(attrs.ngModel, function (current, old) {
ctrl.$render()
}, true)
}
return {
require: 'ngModel',
restrict: 'E',
link: link,
//if isolated scope is not set it is working fine
scope: true,
template: '<div><input type="button" class="one" value="One"/><input type="button" class="two" value="Two"/><span class="result"></span></div>',
replace: true
};
}]);
演示:小提琴
如果未设置隔离范围,则可以正常工作:小提琴