1

Hi I am quite new to angular programming and I had a question on angular's ng-options.

I have an object structure like

TestObj: { name: 'Name1', subNames: ['Subname1'] }
TestArr:
    [{ name: 'Name1', subNames: ['Subname1'] },
    { name: 'Name2', subNames: ['Subname1'] },
    { name: 'Name3', subNames: ['Subname1'] }]

And I am trying to use ng-options to bind one of the TestArr objects to TestObj.

<select class="touchpoint-settings-create-channel-box ng-model="TestObj" ng-options="curTest.name for curTest in TestArr"></select>

However, is there any way to make TestObj bind to the object in TestArr that has the same 'name' property?

This jsfiddle is a good example of what I mean. http://jsfiddle.net/KN9xx/840/

When it first starts up, selectedPerson is set to an object similar to the first item in the array, but ng-options does not realize it is the same object.

Thank you

James
  • 557
  • 1
  • 12
  • 29

1 Answers1

2

I would not recommend following the example in that jsfiddle. Essentially, you do not want TestObj AND TestArr. If TestObj is not just a reference to TestArr, they are not going to be the same object and you're duplicating data because Angular and JavaScript do not recognize that the two objects have the same keys and values when they are separate objects.

You should follow the example in this SO post: How to have a default option in Angular.js select box

Rather than using TestObj like you are, use ng-init to set the default value.

var TestArr =
    [{ name: 'Name1', subNames: ['Subname1'] },
    { name: 'Name2', subNames: ['Subname1'] },
    { name: 'Name3', subNames: ['Subname1'] }];

<select
  class="touchpoint-settings-create-channel-box
  ng-init="TestObj = options[0]"
  ng-model="TestObj"
  ng-options="option.name for option in TestArr">
</select>

To illustrate my point on objects:

var obj1 = { name: 'Me' };
var obj2 = { name: 'Me' };

While obj1 and obj2 look exactly the same, the variables are just references to the underlying object, not the values, and the JS interpreter doesn't know that I intend both of those objects to be the same. However, if you strings or numbers, it works like you expect.

var me = 'Me';
var stillMe = 'Me';

console.log(obj1 === obj2); // prints false
console.log(me === stillMe); // prints true
Community
  • 1
  • 1
EmptyArsenal
  • 7,314
  • 4
  • 33
  • 56