如何在 ng-click 指令上获取列值并与 scope.info 绑定

How get col value on ng-click directive and bind with scope.info

<grid-sort col="lMember_id" variable="lMember_id"></grid-sort>

指令

app.directive("gridSort", function () {
    return {
        template:
          '<button  ng-click="Direction=-1;SetSortValue();orderBy();" ng-init="info.CurrentPage=0"><i class="fa-angle-double-up fa"></i></button>' +
          '<button  ng-click="Direction=1; SetSortValue();orderBy();" ng-init="info.CurrentPage=1000"><i class="fa-angle-double-down fa"></i></button>'
        ,
        link: function (scope, element, attrs) {
            scope.SetSortValue = function () {   
                if (scope.Direction == -1) {
                    scope.info.CurrentPage = 0;
                    scope.info.Direction = 'Asc';

                }
                else if (scope.Direction == 1) {
                    scope.info.Direction = 'Desc';
                    scope.info.CurrentPage = 1000;

                }
            }
        }
    };
});

我的控制器在 ng-click 上

$scope.orderBy = function () {
   var data = $scope.info;
   Request.GetTabledata("SelectMemberData", data, $scope, true);
};

我想将 col 属性值与 scope.info.colname 绑定。当我声明范围时,orderBy() 方法不起作用。当我没有声明范围时,所有方法都有效但我无法获得 col 值

更新:啊,现在我明白你想要达到什么目的了!如果您只使用该指令一次,您的方法可能会起作用 - 但由于您多次使用它,您最终会覆盖指令属性 您的 $scope 变量。

您可以通过使用 子作用域 来解决这个问题,即:不要与父作用域混合,而是在内部保存变量和方法或 "local" 每个实例的指令。

这是使用子作用域的指令的重构版本,它仅更新子作用域的 $parent info,即您的主要 $scope :

.directive("gridSort", function() {
  return {
    template: 
      '<button  ng-click="Direction=-1;SetSortValue();orderBy();" ng-init="info.CurrentPage=0"><i class="fa-angle-double-up fa"></i>xx</button>' +
      '<button  ng-click="Direction=1; SetSortValue();orderBy();" ng-init="info.CurrentPage=1000"><i class="fa-angle-double-down fa"></i>xx</button>'
    ,
    scope: {
      col: '@',
      variable: '@',
    },
    controller: function($scope) {
      $scope.info = {
        colName: $scope.col
      }
      $scope.SetSortValue = function() {
        if ($scope.Direction == -1) {
          $scope.info.CurrentPage = 0;
          $scope.info.Direction = 'Asc';
        } else if ($scope.Direction == 1) {
          $scope.info.Direction = 'Desc';
          $scope.info.CurrentPage = 1000;
        }
        $scope.$parent.info = $scope.info;
      }
    },
    link: function(scope, element, attrs) {
      //any additional processing
    }
  };
});
  1. 只需向指令添加 scope: {} 文字即可声明子作用域
  2. 模板中的所有引用现在都指向这个子范围
  3. controller: function($scope {}
  4. 中处理子作用域
  5. 通过 $scope.$parent
  6. 定位您的控制器 $scope

演示 -> http://next.plnkr.co/edit/uxiHC9jgebgJc3DW