【问题标题】:Angular-xeditable can not access form by name from controllerAngular-xeditable 无法从控制器按名称访问表单
【发布时间】:2015-05-21 02:25:25
【问题描述】:

我正在尝试在 ng-repeat 中构建 angualr x 可编辑表单,但是当我尝试通过控制器中的 $scope 访问表单时出现错误。

<div ng-repeat="course in box.value track by $index">
   <form editable-form name="{{box.key}}{{$index}}">
      .....
      <button 
         type="button"
         class="btn btn-primary"
         ng-click="formAction(box.key, $index, 'show')">Edit
      </button>
   </form>
</div>

在 JavaScript 中,我有以下内容,但这会在执行时导致错误。

$scope.formAction = function (key, index, action) {
    var formName = key + index;
    if (action === 'show') {
         //console.log(formName) shows correct form name yet
        //Error!! TypeError: Cannot read property '$show' of undefined
        $scope[formName].$show();
    }
};

x-editable 手册说 form name="{{box.key}}{{$index}}" 应该在 $scope 上创建一个属性但是当我 console.log($scope) 我找不到属性

【问题讨论】:

    标签: angularjs angularjs-scope x-editable


    【解决方案1】:

    实际上 x-editable 将表单添加到范围内,但不会添加到 formAction 所在的范围内。 ng-repeat 为它呈现的每个项目创建一个范围,它们是原始范围的子范围,您将在这些范围上找到表单。

    一种解决方案是将子作用域传递给formAction,下面是'this':

    <button 
         type="button"
         class="btn btn-primary"
         ng-click="formAction(box.key, $index, 'show', this)">Edit
    </button>
    

    然后在子范围内找到的表单上调用$show()

    $scope.formAction = function (key, index, action, childScope) {
        var formName = key + index;
        if (action === 'show') {
            childScope[formName].$show();
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多