AngularJS: naming an object property to a directive

I am writing the angular.js directive, which is a reusable input component for an array of objects.

Since it is impossible to use primitive values ​​in ng-repeat(see What is the angularjs method for binding data to multiple inputs? ), I have to pass an array of objects to the component:

In the controller, I initialize:

$scope.theSimpsons = [{ value: 'Bart' }, { value: 'Lisa' }];

And then use it in the HTML file:

<div ng-app="App">
    <div ng-controller="AppCtrl">
        <multi-input items="theSimpsons" />
    </div>
</div>

The directive itself is implemented as follows:

directive('multiInput', function () {
return {
    restrict: 'E',
    scope: {
        items: '=items'
    },
    template:
        '<div>' +
        '<div ng-repeat="item in items">' +
        '<input type="text" ng-model="item.value">' +
        '<a ng-click="items.splice($index, 1)">remove</a>' +
        '</div>' +
        '<a ng-click="items.push({value:\'\'})">add</a>' +
        '</div>'
};
});

It all works well.

My question is: what if the objects do not have value?

This directive coordinates the name of the property ( value). But what if I want to have an array: [{ name: 'Bart' }, { name: 'Lisa' }].

Is it possible to pass the name of the object, for example. as

<multi-input items="names" property="name"></multi-input>

- name?

JSFiddle http://jsfiddle.net/napU6/5/, , .

+5
1

,

<multi-input items="myItems" name="value"></multi-input>

app.directive('multiInput', function(){
  return {
    restrict: 'E',
    replace: true,
    scope: {
      items:'=',
      name: '@'
    },
    template:'<div>'
      + '<div ng-repeat="item in items">'
      + '<input type="text" ng-model="item[name]">'
      + '<a ng-click="items.splice($index, 1)">remove</a>'
      + '</div>'
      + '<a ng-click="items.push({})">add</a>'
      + '</div>'
  }
});

: Plunker

+4

All Articles