Reputation: 370
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?
Upvotes: 2
Views: 3132
Reputation: 125
Use the ng-init in div tag enclosing your text area like this.
<div ng-init="question.question_title=index">
<textarea type="text" name="question_title" ng-model="question.question_title">
</div>
This is supposed to prefill your text area with the data in $scope.question.question_title and make sure in your controller $scope.question is already defined like this.
$scope.question = {
question_title:""
}
Upvotes: 1
Reputation: 2547
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 fromcontroller
inside theview
or set default values for variables (which didn't use asng-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
};
}
Upvotes: 1
Reputation: 2266
I guess it's because you're calling $scope.index= $scope.myJson.Q_id;
inside async method - and that's when ng-inits already fired (can't tell for sure, as there's not enough code provided).
But overall, you probably could use another way than ng-init, as putting app logic inside view is rather bad practice. Why not:
$scope.index= $scope.myJson.Q_id;
$scope.question.question_title= $scope.myJson.Q_id;
Alternatively, there are times when you could defer ng-init with ng-if, like:
<textarea type="text" name="question_title" ng-model="question.question_title" ng-if="index" ng-init="question.question_title=index">
Upvotes: 1