带参数的隔离范围函数

时间:2014-12-10 03:58:34

标签: angularjs

我正在显示一个带有切换开关的表格。当我切换时,应该为该特定行运行切换功能。我使用angular-toggle-switch进行切换。要实现这一点,我需要行的id和切换值。

查看

<tr rec-status ng-repeat='staff in staffs | filter:query | orderBy: sort.field : sort.order'>
    <td ng-repeat='field in fields'>
        {{staff[field]}}
    </td>
    <td>
        <toggle-switch selid="{{staff.id}}" clickhandle="changeStatus()" ng-model="switchStatus" on-label="Active" off-label="Inactive">
        <toggle-switch>
    </td>
</tr>

切换开关指令

scope: {
  disabled: '@',
  onLabel: '@',
  offLabel: '@',
  knobLabel: '@',
  selid:'@',
  clickhandle:'&',
},
link: function(scope, element, attrs, ngModelCtrl){
  if (!attrs.onLabel) { attrs.onLabel = 'On'; }
  if (!attrs.offLabel) { attrs.offLabel = 'Off'; }
  if (!attrs.knobLabel) { attrs.knobLabel = '\u00a0'; }
  if (!attrs.disabled) { attrs.disabled = false; }

  element.on('click', function(e) {
    scope.$apply(scope.toggle);
    e.stopPropagation();
  });

  ngModelCtrl.$formatters.push(function(modelValue){
     return modelValue;
  });

  ngModelCtrl.$parsers.push(function(viewValue){
    return viewValue;
  });

  ngModelCtrl.$render = function(){
      scope.model = ngModelCtrl.$viewValue;
  };

  scope.toggle = function toggle(e) {
    if(!scope.disabled) {
      scope.model = !scope.model;
      ngModelCtrl.$setViewValue(scope.model);
      data = {};
      data['value'] = scope.model;
      data['id'] = attrs.selid;
      scope.clickhandle(data);
    }
  };
}

控制器

$scope.changeStatus = function(data){
    console.log(data);
}

我将未定义作为输出。

但如果我使用scope.clickhandle({value:"true"});其工作

1 个答案:

答案 0 :(得分:0)

根据scope.clickhandle({value:"true"});示例将参数对象传递到函数调用中是在隔离范围内调用&定义的函数的正确方法。根据文档,https://docs.angularjs.org/api/ng/service/ $ compile#scope

  

... isolate scope属性将指向函数包装器 ...

     

通常需要通过表达式将数据从隔离范围传递到父作用域,这可以通过将局部变量名称和值的映射传递到表达式包装器fn来完成。例如,如果表达式是增量(金额),那么我们可以通过将localFn称为localFn({amount:22})来指定金额值