angular中ng-repeat ng-if 中的變量的值控制器中為什么取不到


這個問題的本質是:v-repeat會產生子scope,這時你在控制器里拿值,相當於父scope里面取子scope的值,因為Angular.js中作用域是向上查找的,所以取不到。

操作過程如下:

  

 

 

相關代碼如下:

<table>
    <tr>
        <th>序號</th><th>姓名</th><th>工資</th><th>操作</th>
    </tr>
    <tr>
        <td>{{$index+1}}</td>
        <td>{{item.name}}</td>
        <td><input name="salary" ng-model="salary" /></td>
        <td><button ng-click="myAlert()">彈出工資</button></td>
    </tr>
</table>
<script>
    QryListCtrl.$inject = ['$scope', '$remote'];
    function QryListCtrl($scope, $remote){
        $scope.myAlert = function(){
            alert($scope.salary);
        }
    }
</script>

 解決方法:

<table>
    <tr>
        <th>序號</th><th>姓名</th><th>工資</th><th>操作</th>
    </tr>
    <tr>
        <td>{{$index+1}}</td>
        <td>{{item.name}}</td>
        <td><input name="salary" ng-model="$parent.salary" /></td>
        <td><button ng-click="myAlert()">彈出工資</button></td>
    </tr>
</table>

原理:把子scope中的值通過 $parent屬性傳遞給父scope即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM