在控制器中访问ng-repeat $ first属性

时间:2016-04-26 09:31:41

标签: javascript angularjs

我有一个带有两个输入框的表,使用ng-repeat我已遍历值

<tr ng-repeat = "row in allRows" >
<td>

<input type="text" ng-model="row.name" ng-readonly="toogleRN && $first"/>
</td>
<td>
<input type="number" ng-model="row.age" ng-readonly="toogleRN && $first"/>
 </td>
 <td>
  <a role="button" class="btn btn-sm btn-default "
                         data-ng-click="toogleIt()" data-ng-show="$first"><span class="glyphicon glyphicon-search"> Edit</span>
                      </a>
 </td>
 </tr>
 </table>

我的控制器是我的控制器

var app =  angular.module("TableDemo",[]);
app.controller('TableController',['$scope',function($scope){
    $scope.toogleRN=true;

    $scope.toogleIt= function()
    {
        $scope.toogleRN = !$scope.toogleRN;
        console.log($scope.toogleRN);
    };

    $scope.allRows=[{name:'Name_1',age:25},
                    {name:'Name_2',age:28},
                    {name:'Name_3',age:17},
                    {name:'Name_4',age:25},
                    {name:'Name_5',age:26}];
}]);

要求第一行在默认情况下应该是只读的,当点击&#34;编辑&#34;按钮它应该是可编辑的。通过使用上面的代码,它满足我的要求,但我的问题是如何将ng-readonly="toogleRN && $first"移动到控制器?

4 个答案:

答案 0 :(得分:1)

使用函数:

ng-readonly="myFunction(toogleRN, $first, row.editable)"
// on the button 
 ng-click = row.editable = true
 // in the javascript
 $scope.myFunction = function(toogleRN, isFirt, isEditable){

 }

答案 1 :(得分:0)

你只需要基本的行索引号。您已经拥有控制器中的数据。

所以你可以这样做,

ng-readonly="toogleRN && $index == 0"

答案 2 :(得分:0)

只需添加一个功能

ng-readonly="isReadable($index);"

$scope.isReadable = function($index){
    return (!$index && $scope.toogleRN)
}

答案 3 :(得分:0)

我认为这就是你想要的:

<强> HTML

<table>
    <tr ng-repeat = "row in allRows" >
        <td>
            <input type="text" ng-model="row.name" ng-readonly="isReadonly($index)"/>
        </td>
    <td>
        <input type="number" ng-model="row.age" ng-readonly="isReadonly($index)"/>
    </td>
     <td>
         <a role="button" class="btn btn-sm btn-default "
                     data-ng-click="toogleIt()" data-ng-show="$first"><span class="glyphicon glyphicon-search"> Edit</span>
         </a>
     </td>
     </tr>
</table>

<强> AngularJS

$scope.toogleRN=true;
$scope.isReadonly = function(index) {
    return index == 0 && $scope.toogleRN
}
$scope.toogleIt= function()
{
    $scope.toogleRN = !$scope.toogleRN;
    console.log($scope.toogleRN);
};

$scope.allRows=[{name:'Name_1',age:25},
                {name:'Name_2',age:28},
                {name:'Name_3',age:17},
                {name:'Name_4',age:25},
                {name:'Name_5',age:26}];