导航到另一个页面时如何定位元素(部分)

时间:2020-03-21 22:12:29

标签: angularjs

我有一个复选框,希望根据其他复选框的状态将不确定状态设置为。当我进入所有复选框的页面时,它会按预期更新(即找到该复选框)。但是,当我从另一个页面导航到该页面时,我的方法找不到该复选框(即返回null)。

当我在Chrome devtools中调试时,我注意到

let checkBoxWithIndeterminateState;
let checkbox = false;

fireWhenCheckBoxChanged() {
     // returns null when navigating from another page but not when on its own page
     checkBoxWithIndeterminateState = document.getElementById('checkBoxWithIndeterminateState')
     checkBoxWithIndeterminateState.indeterminate = true
}

模板:

<input type="checkbox" id="checkBoxWithIndeterminateState" data-ng-model="checkbox">

在我的方法尝试找到该复选框之前,如何等待新模板加载完毕?我已经阅读了一些使用this._$scope.$on('$viewContentLoaded'...的建议,但这是行不通的。

谢谢!

1 个答案:

答案 0 :(得分:1)

如何在目标复选框中添加ng-init指令并在其中进行逻辑处理,这样可以确保元素存在,这是一个建议:

<input type="checkbox" ng-init="initTragetCheckbox()">

在您的控制器中

$scope.initTragetCheckbox = function () {
    // your code to execute for other checkboxes
    var checkbox1 = document.getElementById("checkbox1");
    var checkbox2 = document.getElementById("checkbox2");
    ....
}