等待状态数据完成

时间:2019-02-11 12:44:42

标签: angularjs

我有一个指令MenuTabsComponent:

    public $onInit() {
        console.log(this.$state.current.name);
        setTimeout(() => {
            console.log(this.$state.current.name);
        }, 500);
    }

问题在于此代码在所有状态数据可用之前就已执行。如果我在没有setTimeout的情况下运行代码,则$state.name是不正确的。

  

dashboard.tasks.overview.details

     

dashboard.tasks.overview.details.information

但是setTimeout不是正确的解决方案。如何等待状态数据可用?

1 个答案:

答案 0 :(得分:2)

您可以将state.name分配给变量,然后使用$ scope。$ watch来检测更改。

$scope.name = this.$state.current.name;

$scope.$watch(name, function (newValue, oldValue) {

});

您还可以检查oldValue以查看其是否为空,并仅在oldValue为null时才执行代码以执行一次功能。

$scope.$watch(name, function (newValue, oldValue) {
    if(oldValue == null){
        //execute your function
    } 
});
相关问题