How can I make a directive that includes the divs used in the ng-repeat?

My application is using this HTML to do ng-repeat

:

    <div class="gridBody">
        <div ng-class="{clicked: row.current == true}"
             ng-click="home.rowClicked($index)"
             ng-dblclick="ctrl.rowDoubleClicked(row)"
             ng-repeat="row in home.grid.view = (home.grid.data | orderBy:ctrl.examOrderBy[ctrl.configService.admin.examOrderBy].key:ctrl.configService.admin.examSortDirection) track by row.examId">

      

I understand how to do template directives, but I'm not sure if I can make a directive that calls another, like here where it calls ng-repeat

. How can I create a directive that will allow me to call this block of code like this:

    <div grid-body
         order="ctrl.examOrderBy[ctrl.configService.admin.examOrderBy].key"
         direction="ctrl.configService.admin.examSortDirection)"
         track="examId">

      

Basically, I need a directive that combines the two <div>

above into one. I think I need one that uses transclude , but I'm not sure how to use transclude and I couldn't find examples similar to this.

+3


source to share


1 answer


What you really want to do is Isolate Scope

Check My Plunker

Like your code, I am using ng-repeat:

<div employeeform ng-repeat="emp in emplList" passed-model="emp">
</div>

      

employeeform

is my attribute directive. It is defined with its own isolated area and controller:

empApp.directive('employeeform', [
  function($compile) {

    function RowController($scope) {
      $scope.smyClass = "none";
      $scope.clickMe = function() {
        if ($scope.smyClass == "none") {
          $scope.smyClass = "clicked";
        } else {
          $scope.smyClass = "none";
        }
      };    
    }

    return {
      restrict: "A",
      controller: RowController,
      replace: true,
      scope: {
        passedModel: '='
      },
      templateUrl: "Employee.html"
    };
  }
]);

      

The template Employee.html

has links to local control scope functions and the smyClass property:



<div class="{{smyClass}}" ng-click="clickMe()" >
  <div style="display:inline-block; width: 100px;">{{ passedModel.name }}</div>
  <div style="display:inline-block; width: 100px;">{{ passedModel.position }}</div>
  <div style="display:inline-block; width: 100px;">{{ passedModel.salary }}</div>
</div>

      

Since I didn't have your data or other source, I created a simple tabular report. When you click on any line, the background turns yellow. When you depress each line, it goes back to normal white. This is my way of simulating click and unclick.

Summary:

If the directive has a specific local scope:

  scope: {
    passedModel: '='
  },

      

it has nothing to do with the parent scope other than the passed parameters (like passModel). This gives you the ability to use local variables to define the class of that particular string (directive).

+3


source







All Articles