Skip to content

Commit c62ff4b

Browse files
authored
Merge pull request #705 from kyse/development
Improve sfNewArray Directive's titleMapValues Binding
2 parents 59e4e2c + 66e342e commit c62ff4b

File tree

2 files changed

+56
-8
lines changed

2 files changed

+56
-8
lines changed

src/directives/newArray.js

+5-8
Original file line numberDiff line numberDiff line change
@@ -120,15 +120,12 @@ function(sel, sfPath, schemaForm) {
120120
if (vals && vals !== old) {
121121
var arr = getOrCreateModel();
122122

123-
// Apparently the fastest way to clear an array, readable too.
124-
// http://jsperf.com/array-destroy/32
125-
while (arr.length > 0) {
126-
arr.pop();
127-
}
128-
form.titleMap.forEach(function(item, index) {
129-
if (vals[index]) {
123+
form.titleMap.forEach(function (item, index) {
124+
var arrIndex = arr.indexOf(item.value);
125+
if (arrIndex === -1 && vals[index])
130126
arr.push(item.value);
131-
}
127+
if (arrIndex !== -1 && !vals[index])
128+
arr.splice(arrIndex, 1);
132129
});
133130

134131
// Time to validate the rebuilt array.

test/directives/schema-form-test.js

+51
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,57 @@ describe('directive',function(){
817817
});
818818
});
819819

820+
it('should not clear the model when using multiple checkboxes targeting the same model array', function () {
821+
822+
inject(function ($compile, $rootScope) {
823+
var scope = $rootScope.$new();
824+
scope.person = {
825+
"names": ["foo"]
826+
};
827+
828+
scope.schema = {
829+
"type": "object",
830+
"properties": {
831+
"names": {
832+
"type": "array",
833+
"items": {
834+
"type": "string",
835+
"enum": ["foo", "bar"]
836+
}
837+
}
838+
}
839+
};
840+
841+
scope.form = [
842+
'names',
843+
'names',
844+
{ key: "names", type: "checkboxes", titleMap: { 'foo': 'Foo', 'bar': 'Bar' } },
845+
{ key: "names", type: "checkboxes", titleMap: { 'foo': 'Foo', 'bar': 'Bar' } }
846+
];
847+
848+
var tmpl = angular.element('<form sf-schema="schema" sf-form="form" sf-model="person"></form>');
849+
850+
$compile(tmpl)(scope);
851+
$rootScope.$apply();
852+
853+
var foo = tmpl.children().eq(0).find('input[type=checkbox]').eq(0);
854+
var bar = tmpl.children().eq(3).find('input[type=checkbox]').eq(1);
855+
856+
foo.prop('checked').should.be.true;
857+
bar.prop('checked').should.be.false;
858+
scope.person.names.length.should.be.equal(1);
859+
scope.person.names.join(',').should.be.equal('foo');
860+
861+
bar.click()
862+
scope.person.names.length.should.be.equal(2);
863+
scope.person.names.join(',').should.be.equal('foo,bar');
864+
865+
foo.click();
866+
scope.person.names.length.should.be.equal(1);
867+
scope.person.names.join(',').should.be.equal('bar');
868+
});
869+
});
870+
820871
it('should use radio buttons when they are wanted',function(){
821872

822873
inject(function($compile,$rootScope){

0 commit comments

Comments
 (0)