Search code examples
angularjsdata-bindingangularjs-directivetwo-way

AngularJS two way binding variables to array items


To view my code follow this link

I've created a directive which handles an array of items (it will always be two because it's a "from" and "to" date pair).

I want to make the array items accessible as separate values for later use so I refer to the array items like this

  vm.data = ['data a', 'data b'];
  vm.separateData = vm.data[0];
  vm.otherData = vm.data[1];

When I implement a two way bind into the directive, the vm.data[0] and vm.data[1] references are updated but the vm.separateData and vm.otherData aren't.

Is there a way of making this work or should I just restructure the rest of my app (where needed) to accomodate for array items?

In my fiddle link (same as above) try changing the text input values and you'll see what I mean.


Solution

  • vm.data[0] is a string and thus it is a primitive datatype in javascript which is immutable. So you bind the immutable String 'Data a' to vm.separateData, which is not a reference to data[0].

    If you want to copy the reference to the array into vm.separateData try to wrap your strings in other javascript objects, e.g.

    vm.data = [{"value":"Data a"}, {"value":"Data b"}]
    

    and then you can reference

    vm.separateData = vm.data[0];
    

    and access the value via

    vm.separateData.value