javascripthtmlangularjsangular-ngmodelng-init

Using ng-init to bind a variable to a value in my controller


I'm working on an editor page. I receive a Json from my server, that contains:

{
    "Q_id": 1,
    "isMultipuleAns": 0,
    "Q_mediaType": "page"
}

And I'm trying to put the information in input div (type=text) or textarea div.

<textarea 
    type="text" 
    name="question_title" 
    ng-model="question.question_title" 
    ng-init="question.question_title=index"`>

and in my controller I have something like this:

app.controller("someController",function($scope,$location,$http){
    // some http requests that puts the mentioned jason in $scope.myJson
    $scope.index= $scope.myJson.Q_id;
}

And no matter what I try, ng-init only works with a static string. I can't get the real ID to appear on the site. Only gets a blank input field.

I am new to html and or angular... help?


Solution

  • You can't use ng-init in your input as you did, that because it work at start of your project when your view is coming up.

    so what ng-init do for me !?

    ng-init used for calling functions from controller inside the view or set default values for variables (which didn't use as ng-model) for example:

     var controller = function($scope){
       $scope.makeNewId = function(){
          return 15899933666;
       }
     }
    

    in this sample we can call $scope.makeNewId() directly in the controller also we can do it when our view is compile as ng-init="makeNewId()", and if you attention it work on each page reload

    so what's wrong with my codes!

    in your codes you want to set ng-model value with ng-init, completely wrong

    if you ask why, that because you use something like this question.question_title that means you have a object which name is question; so i can easily define it in my controller:

     var controller = function($scope){
        $scope.question = {
          question_title: $scope.myJson.Q_id
        };
     }