diff --git a/src/directives/newArray.js b/src/directives/newArray.js index 7acdb99d6..deffdc33e 100644 --- a/src/directives/newArray.js +++ b/src/directives/newArray.js @@ -120,15 +120,12 @@ function(sel, sfPath, schemaForm) { if (vals && vals !== old) { var arr = getOrCreateModel(); - // Apparently the fastest way to clear an array, readable too. - // http://jsperf.com/array-destroy/32 - while (arr.length > 0) { - arr.pop(); - } - form.titleMap.forEach(function(item, index) { - if (vals[index]) { + form.titleMap.forEach(function (item, index) { + var arrIndex = arr.indexOf(item.value); + if (arrIndex === -1 && vals[index]) arr.push(item.value); - } + if (arrIndex !== -1 && !vals[index]) + arr.splice(arrIndex, 1); }); // Time to validate the rebuilt array. diff --git a/test/directives/schema-form-test.js b/test/directives/schema-form-test.js index a34553c86..975b2863b 100644 --- a/test/directives/schema-form-test.js +++ b/test/directives/schema-form-test.js @@ -817,6 +817,57 @@ describe('directive',function(){ }); }); + it('should not clear the model when using multiple checkboxes targeting the same model array', function () { + + inject(function ($compile, $rootScope) { + var scope = $rootScope.$new(); + scope.person = { + "names": ["foo"] + }; + + scope.schema = { + "type": "object", + "properties": { + "names": { + "type": "array", + "items": { + "type": "string", + "enum": ["foo", "bar"] + } + } + } + }; + + scope.form = [ + 'names', + 'names', + { key: "names", type: "checkboxes", titleMap: { 'foo': 'Foo', 'bar': 'Bar' } }, + { key: "names", type: "checkboxes", titleMap: { 'foo': 'Foo', 'bar': 'Bar' } } + ]; + + var tmpl = angular.element('
'); + + $compile(tmpl)(scope); + $rootScope.$apply(); + + var foo = tmpl.children().eq(0).find('input[type=checkbox]').eq(0); + var bar = tmpl.children().eq(3).find('input[type=checkbox]').eq(1); + + foo.prop('checked').should.be.true; + bar.prop('checked').should.be.false; + scope.person.names.length.should.be.equal(1); + scope.person.names.join(',').should.be.equal('foo'); + + bar.click() + scope.person.names.length.should.be.equal(2); + scope.person.names.join(',').should.be.equal('foo,bar'); + + foo.click(); + scope.person.names.length.should.be.equal(1); + scope.person.names.join(',').should.be.equal('bar'); + }); + }); + it('should use radio buttons when they are wanted',function(){ inject(function($compile,$rootScope){