首次初始化后如何避免ng-init

时间:2015-02-13 18:09:34

标签: angularjs angularjs-ng-init

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

这是我的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?

1 个答案:

答案 0 :(得分:1)

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

我说而不是这样做你可以将你的变量设置在角度的角度运行/配置阶段。

<强> CODE

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

希望这可以帮到你。