In my custom Angular directive (v1.4.3), I am passing two bindings.
- The first binding is an Object with 2-way binding (model: '=') that can either be an Array or a single Object like [{something: 'foo'}, {something: 'moo'}, ...] or just {something: 'foo', other: 'test'}
- The second binding is a look-up for the model in that Object (lookUp: '@'). It is a string that specifies the path to locate the desired data within the directive. For example, '[0].something' or '.something'.
I have implemented a function to retrieve the data based on the provided string, but it causes the 2-way binding to break because any updates made to the extracted data are not reflected in the original model Object.
The function I am using to extract data with a string key is:
Object.resolve = function (path, obj, safe) {
return path.split('.').reduce(function (prev, curr) {
return !safe ? prev[curr] : (prev ? prev[curr] : undefined)
}, obj || self)
}
vm.data = Object.resolve(vm.lookUp, vm.model); // retrieves the necessary data for display and editing but disrupts the binding to vm.model
Is there a more Angular-friendly approach to achieve this while maintaining the binding?