【问题标题】:how to avoid ng-init after first initialization第一次初始化后如何避免 ng-init
【发布时间】:2015-02-13 18:09:34
【问题描述】:

我在我的应用程序中使用 ng-init 来初始化一个变量。问题是我在加载应用程序后更改此变量,并且我希望我首先初始化的变量在函数执行后存储新值。我是 Angular 新手,无法弄清楚...

这是我的ng-init

<tr ng-repeat="(script_id, cron_format) in row" **ng-init**="oldCron = cron_format">
    <td>{{user_id}}</td>
    <td>{{script_id}}</td>
    <td>
       <input type="text" ng-model="cron_format" ng-blur="saveCron(user_id,script_id,cron_format,oldCron)"/>
    </td>
</tr>

saveCron() 应该改变oldCron 的值,但是每次我调用该函数时,它都会用ng-init 中的值初始化oldCron。 这是我尝试提交更改的功能:

$scope.saveCron = function(userId,scriptId,cronFormat,oldCron){
    if (oldCron != cronFormat) {
        oldCron = cronFormat;
        $http.post("updateCronChange.php",cron_format=" + cronFormat, function (data) {
            alert('cron format changed to:' + cronFormat);
        });
    }
}

知道如何在第一次初始化后更新oldCron 并忽略 ng-init 吗?

【问题讨论】:

    标签: angularjs angularjs-ng-init


    【解决方案1】:

    我们无法满足您的要求,因为在呈现 HTML 时会调用 ng-init

    我想说的是,您可以在 angular 的 angular run/config 阶段中设置变量,而不是这样做。

    代码

    app.run(function($rootScope, myService){
     //set the variable inside $rootScope, this will available for any controller
     $rootScope.myVariable = 'setFromRunPhaseUsingRootScope';
     //you can use sharable service variable to set data, and use that inside your controller
     myService.myVariable = 'setFromRunPhaseUsingService'
    });
    

    希望这对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2021-10-28
      • 1970-01-01
      • 2019-08-04
      • 2018-02-17
      • 1970-01-01
      相关资源
      最近更新 更多