Search code examples
angularjsangular-ui-grid

Use the same template on different scopes


I have a ui-grid that allows users to select a row:

angular.module("app").component("mycomponent", {
  templateUrl: "View.html",
  controllerAs: "m",
  controller: [Interactor_Controller]
})


function Interactor_Controller() {
  var m = this
  m.gridOptions = {enableRowSelection: true, enableRowHeaderSelection: false}
  m.gridOptions.columnDefs = [
    {field: "id"},
    {field: "name"}
  ]
  m.gridOptions.multiSelect = false

  m.gridOptions.onRegisterApi = function(gridApi){
    m.infoGridApi = gridApi
    gridApi.selection.on.rowSelectionChanged(null, function(row){
      m.infoGridSelectedRow = row.entity
    })
  }

  $http
    .get('lottastuff')
    .success(response => {
      m.gridOptions.data = response 
      m.gridApi.selection.selectRow(m.gridOptions.data[0]);
      m.gridSelectedRow = m.gridApi.selection.getSelectedRows()
    })
}

The template would be just a ui-grid invocation:

<div class="gridStyle" ui-grid="m.gridOptions" ui-grid-selection></div>

I'd like to be able to do something like this:

<div class="container-fluid">
  <div class="xs-col-12">
    <myReusableGrid>
  </div>
</div>

(Where the scope is implied because the component is using that page as it's template).

This works when it's built inside a controller, but I need to

  • Reuse in multiple views
  • Get data from the controller
  • Send the selected row to the controller and the view it's being inserted into.

What should I use to accomplish this? Directive? Factory? Template? Something else? I'm not exactly sure how to do most of that, but I want to make sure I'm on the right track before I spend time figuring it out (time is essential).

  • How do I send data from the controller?

  • How do I send data to the controller?


Solution

  • I recommend you use a Component.

    In AngularJS, a Component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure.

    This makes it easier to write an app in a way that's similar to using Web Components or using the new Angular's style of application architecture.

    Source: https://docs.angularjs.org/guide/component

    I really like components because is write a controller for a specific part of your view, instead of a state.

    Also, take the components path in angularjs, will make easier to you learn Angular (aka angular2).

    This tutorial help me a lot: https://tests4geeks.com/build-angular-1-5-component-angularjs-tutorial/