1

im using ng-init in my app to initalize a variable. problem is i am changing this variable after app is loaded and i want the variable i first initialized to store new value after function executes. im new to angular and couldn't figure it out...

this is my 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>

and saveCron() should change the value of oldCron, but every time i call the function it initializes oldCron with the value in ng-init. this is the function with my attempt to commit the change:

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

any idea how can i update oldCron and ignor ng-init after first initialization??

Al.s
  • 300
  • 4
  • 20

1 Answers1

1

We can't do what you required, becuase ng-init gets called while rendering HTML.

I'd say rather than doing this you could set your variable inside angular run/config phase of angular.

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

Hope this could help you.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299