2

I am trying to initialize my model discharge.total with value 0,such that text box is by default populated with 0. But textbox is not prepopulating.

  • Please Note:

  • I dont want model to initialize in controller.

  • I have already initialized $scope.discharge = {} in controller

<body ng-app>
     <div ng-controller="testController" >
        <input ng-init="discharge.total = 0 " class=" form-control" type="text" ng-model="discharge.total" disabled>       
      </div>
</body>
Gyanesh Gouraw
  • 1,991
  • 4
  • 23
  • 31
  • 1
    You should init object in controller rather using `ng-init`. – Vineet Dec 04 '15 at 09:31
  • @Vineet my controller has already list full of variable initialization. I know its best practise but currently i am trying to achieve the solution this way. – Gyanesh Gouraw Dec 04 '15 at 09:32
  • 1
    Your code is working for me... – Vi100 Dec 04 '15 at 09:40
  • From angular https://docs.angularjs.org/api/ng/directive/ngInit - This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope. – Vineet Dec 04 '15 at 09:40
  • 3
    since you have `$scope.discharge = {}` it is very simple to do this `$scope.discharge = {total: 0}` – koox00 Dec 04 '15 at 09:42
  • http://jsfiddle.net/53hznu57/ – Gyanesh Gouraw Dec 08 '15 at 10:16

1 Answers1

2

ngInit is used to evaluate expressions. Check how its used here.

you can do something like this though

 <div ng-init="discharge.total = 5">
        {{discharge.total}}
      </div>

check why yours wont work is here

  <input ng-init="discharge = 0 " class=" form-control"
 type="text" ng-model="discharge.total" disabled>{{discharge}}</input>
Community
  • 1
  • 1
Vasu Sheoran
  • 215
  • 1
  • 6
  • 1
    which way, it works with
    , check the first fiddle. Also i edited it a little bit, [new fiddle](http://jsfiddle.net/k23ya4m9/) is this what you want ??
    – Vasu Sheoran Dec 08 '15 at 09:46