将变量作为ngModel传递给属性指令

时间:2017-05-30 07:26:31

标签: javascript html angularjs

假设我有以下表格行:

<tr ng-repeat="item in tableData track by item.id" 
    row-operation-directive="item">

以下指令:

angular.module('LBTable').directive('rowOperationDirective', function () {
    return{
        restrict: 'A',
        scope:{
            item: '=ngModel'
        },
        link:function (scope, element, attr, ngModel) {

            var i = scope.item;
        }
    }
});

任何人都可以告诉我为什么这不起作用(范围内的项目是undefined

2 个答案:

答案 0 :(得分:2)

只需在另一个参数中解析您的项目,而不是在指令属性本身中解析。您无法访问direcitve CDATA本身的$scope参数。这样就可以像 demo fiddle 一样工作。

视图

<div ng-controller="MyCtrl">
  <table>
    <tr ng-repeat="item in myData track by item.id" 
        row-operation-directive 
        my-item="item">
      <td>{{ item }}</td>
    </tr>
  </table>
</div>

指令

myApp.directive('rowOperationDirective', function () {
    return{
        restrict: 'A',
        scope:{
            item: '=myItem'
        },
        link:function (scope, element, attr, ngModel) {
            var i = scope.item;
            console.log(i);
        }
    }
});

答案 1 :(得分:-1)

为此,您需要将元素更改为:

           rlProductOptionQuantityTxt =1;

将范围更改为:item:“=”

相关问题