简体   繁体   中英

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

Try this,

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

try this html

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

app.js code

please set $scope.cus_traderType your main controller
like this

$scope.cus_traderType = '';
$scope.init=function(){

 $scope.cus_traderType = $scope.traderTypes[1];

 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM