H Varma H Varma - 6 days ago 6
AngularJS Question

Facing issue with ng-init for dynamic data

ng-init with dynamic data is not working

Below is my html with the select field in div.

<div class="form-group">
<div class="col-lg-4">
<select name="trader" class="form-control" id="select" ng-model="$root.customerDetails.traderType"
ng-init="$ctrl.initi()" ng-options="traderTypeObj.description for traderTypeObj in traderTypes
track by traderTypeObj.type" >
</select>
</div>


Now I need to display the first option in the select field by default which I get from a service.So Iam using ng-init.But it is not working .So Iam trying to call a function from ng-init.

If I set this
$rootScope.customerDetails.traderType=$scope.traderTypes[1];
the will display the first option by default.I tested this by taking a button and setting that onclick and its working.So now I tried to call that fuction using ng-init and using $scope.$apply()

this.initi=function(){
$rootScope.customerDetails.traderType = $scope.traderTypes[1];
$scope.$apply();
};


When first time it loads giving the html as error and from second time it is giving
Error: [$rootScope:inprog] $digest already in progress


The issue is Iam calling the value before the ajax service is being called ...

How can I get that option being set..Can please someone help me

Answer

Try this,

   this.initi=function(){
     $timeout(function() {
       $rootScope.customerDetails.traderType = $scope.traderTypes[1];   
       $scope.$apply();
    })
    };
Comments