簡體   English   中英

AngularJS復選框ng模型在控制器內部動態更改值

[英]Angularjs checkbox ng-model changing values inside controller dynamically

我有一個頁面,基本上可以從數據庫中加載數據並將其顯示在網格中-如果您單擊按鈕,它將刷新數據,但是還有一個復選框將導致其自動刷新。 這是HTML代碼:

 <div id="TestViewTable" ng-controller="testTableManager" ng-init="loadTableData()">
    <div><h3>Test Status</h3>
        Search: <input placeholder="Search..." type="text" ng-model="TestViewTableGrid.quickFilterText"/>
        <button id="refresh" ng-click="loadTableData()">Refresh</button>
        <input type="checkbox" ng-model="automaticRefreshFlag">Auto Refresh</input>
            <div ag-grid="TestViewTableGrid" style="width: 1200px;height: 400px;" class="ag-fresh"></div>
            <div >row(s): {{rowCount}}</div>
            <h3>Test Status Output:</h3>
            <textarea rows="100" id="consoleOutput"
                    style="max-height:500px;min-height:200px;width: 1200px;resize: none">
                    {{selectedRowOutput}}
            </textarea>
            <link id=lastOutputComp></link>
        </div>  
    </div>

在控制器內部,我將值初始化為false:

 angular.module('trmApp').controller('testTableManager', function($scope, $http, $timeout, $mdDialog, $mdMedia,  $interval) {

$scope.automaticRefreshFlag = false;

然后,使用$ interval觀察它並根據其設置刷新數據:

    $interval(function(){ $scope.reload(); }, 10000);
$scope.reload = function() {
    if($scope.automaticRefreshFlag) {
        console.log("Automatic Refresh Enabled")
        $scope.loadTableData();
    } else {
        console.log("Automatic Refresh Disabled")
    }
};

問題是當它運行時,在控制台中我看到該值在true和false之間來回切換,而沒有用戶的任何輸入:

>Automatic Refresh Disabled
>TestViewTable.js:185 Automatic Refresh Disabled
>TestViewTable.js:185 Automatic Refresh Disabled
>TestViewTable.js:182 Automatic Refresh Enabled

有人知道我在做什么錯嗎? 謝謝!

Angularjs有時無法跟蹤分配給$ scope的原始類型變量。 因此,您最好創建一個對象,並將automaticRefreshFlag屬性設置為該對象的屬性,然后改用該對象。

angular.module('trmApp').controller('testTableManager', function($scope, $http, $timeout, $mdDialog, $mdMedia,  $interval) { 
$scope.flag = {}; 
$scope.flag.automaticRefreshFlag = false;

對於html部分,請使用

 <input type="checkbox" ng-model="flag.automaticRefreshFlag">Auto Refresh</input>

然后將控制器更改為

$interval(function(){ $scope.reload(); }, 10000);
$scope.reload = function() {
    if($scope.flag.automaticRefreshFlag) {
        console.log("Automatic Refresh Enabled")
        $scope.loadTableData();
    } else {
        console.log("Automatic Refresh Disabled")
    }
};

嘗試這個。 這樣可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM