Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

fix(ngChecked): ensure that ngChecked doesn't interfere with ngModel #10664

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions src/ng/directive/attrs.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,22 +341,34 @@

var ngAttributeAliasDirectives = {};


// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
// binding to multiple is not supported
if (propName == "multiple") return;

function defaultLinkFn(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
}

var normalized = directiveNormalize('ng-' + attrName);
var linkFn = defaultLinkFn;

if (propName === 'checked') {
linkFn = function(scope, element, attr) {
// ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
if (attr.ngModel !== attr[normalized]) {
defaultLinkFn(scope, element, attr);
}
};
}

ngAttributeAliasDirectives[normalized] = function() {
return {
restrict: 'A',
priority: 100,
link: function(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
}
link: linkFn
};
};
});
Expand Down
16 changes: 16 additions & 0 deletions test/ng/directive/booleanAttrsSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ describe('boolean attr directives', function() {
}));


it('should not bind checked when ngModel is present', inject(function($rootScope, $compile) {
// test for https://github.com/angular/angular.js/issues/10662
element = $compile('<input type="checkbox" ng-model="value" ng-false-value="\'false\'" ' +
'ng-true-value="\'true\'" ng-checked="value" />')($rootScope);
$rootScope.value = 'true';
$rootScope.$digest();
expect(element[0].checked).toBe(true);
browserTrigger(element, 'click');
expect(element[0].checked).toBe(false);
expect($rootScope.value).toBe('false');
browserTrigger(element, 'click');
expect(element[0].checked).toBe(true);
expect($rootScope.value).toBe('true');
}));


it('should bind selected', inject(function($rootScope, $compile) {
element = $compile('<select><option value=""></option><option ng-selected="isSelected">Greetings!</option></select>')($rootScope);
jqLite(document.body).append(element);
Expand Down