0

I'm trying to create a list component that is bound to a list defining column metadata and row values. For example:

var list = {
  cols: [
    { name: "date", display: "Date", type: "date" },
    { name: "revenue", display: "Revenue", type: "dollars" }
  ],
  data: [
    { date: "1/2/34", revenue: 10 },
    { date: "2/3/45", revenue: 20 },
    ....
  ]
}

This is simple enough using ng-repeat to iterate over the rows then another ng-repeat to iterate over columns, looking something like this:

<tr ng-repeat="row in list.data">
  <td ng-repeat="col in list.cols">
    {{ row[col.name] }}
  </td>
</tr>

I also want this list to be editable and support multiple types of controls, so my table looks more like this:

<tr ng-repeat="row in list.data">
  <td ng-repeat="col in list.cols">
    <span ng-if="editing == $parent.$index" ng-switch on="col.type">
      <input ng-switch-default ng-model="row[col.name]">
      <span ng-switch-when="pselect" pselect="col.options" ng-model="row[col.name]"></span>
    </span>
    <span ng-if="editing != $parent.$index" ng-switch on="col.type" ng-click="editRow($parent.$parent.$index)">
      <span ng-switch-when="dollars">{{row[col.name] | currency}}</span>
      <span ng-switch-default>{{row[col.name]}}</span>
    </span>
  </td>
</tr>

The pselect in this example is my custom dropdown directive. My goal is to be able to use ng-model inside of this directive to bind its value to an object in the list directive scope (which is bound to my outer scope). My problem arises when trying to sync the model value between pselect's isolate scope and outer scopes. Since the isolate scope is shared between the pselect and ng-model directives, the ng-model directive becomes separated from the containing scope. I have been using this workaround (https://stackoverflow.com/a/15272359/1655272) to sync changes between scopes:

scope.$watch("model", function() {
  scope.$eval(attrs.ngModel + " = model");
});

scope.$watch(attrs.ngModel, function(val) {
  scope.model = val;
});

But with this method, I run into a problem inside the ng-repeat of my list component. Note that on the pselect control ng-model="row[col.name]". The previous method fails when trying to create a local scope variable called row[col.name] as row is undefined. If I create a variable scope.row = {} this error is averted, but this is just a hack.

Has anyone run into a similar problem before? I feel like I am overlooking a more obvious solution, but I can't seem to get a handle on the interactions between directives and scopes.

Community
  • 1
  • 1
scleaver
  • 246
  • 1
  • 3

0 Answers0