我试图写一个使用隔离范围和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 }; }]);
演示:Fiddle
如果隔离示波器没有设置,它工作正常:fiddle