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

时间:2018-08-11 07:13:04

标签: angularjs angularjs-directive

<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绑定。当我声明scope时,orderBy()方法不起作用。当我没有声明作用域时,所有方法都有效,但我无法获得col值

1 个答案:

答案 0 :(得分:1)

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

您可以通过使用子范围来解决此问题,即:不要将变量和方法与内部范围或“本地”保留在指令的每个实例中,而不必与父范围混合。

这是使用子作用域的指令的重构版本,该子作用域仅更新子作用域的$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. 定位您的控制器$scope$scope.$parent

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