运行AngularJS初始化code时的观点是装 [英] Running AngularJS initialization code when view is loaded

查看:84
本文介绍了运行AngularJS初始化code时的观点是装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我打开一个观点,我想在其相关的控制器上运行一些初始化code。

When I load a view, I'd like to run some initialization code in its associated controller.

要做到这一点,我已经使用了NG-初始化指令我的观点的主要元素:

To do so, I've used the ng-init directive on the main element of my view:

<div ng-init="init()">
  blah
</div>

和在控制器:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
        });
    } else {
       //create a new object
    }

    $scope.isSaving = false;
}

第一个问题:这是做正确的方式?

First question: is this the right way to do it ?

接下来的事情,我有发生事件的顺序有问题。在视图我有一个保存按钮,它采用NG-禁用指令这样:

Next thing, I have a problem with the sequence of events taking place. In the view I have a 'save' button, which uses the ng-disabled directive as such:

<button ng-click="save()" ng-disabled="isClean()">Save</button>

isClean()函数是在控制器中定义

the isClean() function is defined in the controller:

$scope.isClean = function () {
    return $scope.hasChanges() && !$scope.isSaving;
}

正如你所看到的,它使用了$ scope.isSaving标志,这是在init()函数初始化。

As you can see, it uses the $scope.isSaving flag, which was initialized in the init() function.

问题:视图加载时,将isClean函数被调用的之前的init()函数,因此标志isSaving是不确定的。我可以做prevent什么?

PROBLEM: when the view is loaded, the isClean function is called before the init() function, hence the flag isSaving is undefined. What can I do to prevent that ?

推荐答案

当您的视图负荷,所以不相关控制器。而是采用NG-的init,只需调用你的init()方法在你的控制器:

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

由于控制器NG-初始化之前运行,这也解决了你的第二个问题。

Since your controller runs before ng-init, this also solves your second issue.

小提琴

由于约翰·戴维·五提到的,你可能不希望为了使这个这个附加到 $范围方法私有的。

As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

见的jsfiddle

这篇关于运行AngularJS初始化code时的观点是装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆