【问题标题】:Angularjs checkbox ng-model changing values inside controller dynamicallyAngularjs复选框ng-model动态更改控制器内的值
【发布时间】:2018-02-21 07:05:44
【问题描述】:

我有一个页面,基本上它从数据库加载数据并将其显示在网格中 - 如果您单击按钮,它将刷新数据,但还有一个复选框会导致它自动刷新。这是 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")
    }
};

问题在于,当它运行时,在控制台中我看到该值在真假之间来回切换,而没有用户的任何输入:

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

有谁知道我做错了什么?谢谢!

【问题讨论】:

  • 请发帖$scope.loadTableData()内容

标签: javascript jquery angularjs


【解决方案1】:

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")
    }
};

试试这个。这将解决您的问题。

【讨论】:

  • 这行得通 - 仅供参考,删除标志值声明为 false ($scope.automaticRefreshFlag = false;) 也解决了这个问题。谢谢!
  • 但是当你一次又一次地切换它时它可能会表现得很奇怪。
  • 你能帮我解决这个问题吗?stackoverflow.com/questions/56231178/…
猜你喜欢
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 2012-09-19
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
相关资源
最近更新 更多