Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ng-model data in controller using angularjs

I have a string containing Json data which is being generated by some another script(lets say script A). I have to access this data using ng-model. So what i tried is that i created an input field like below and attached ng-model to it.

`<input type="text" id="check" name="jsonName" ng-model="saveJson"></input>`

Now what i did is I stored the Json data into this input field using script A like below

document.getElementById("check").value = saveJson;

Now to access this data into angular i created a controller like

    angular.module('myapp').controller('formDataController', ['$scope',
    function($scope){
        $scope.saveForm = function(){
            console.log($scope.saveJson);
        }
    }
]);

where saveForm is a method which is called on a button click using ng-click

Now the problem is until there is any interaction in input field the $scope.saveJson gives an undefiend value. But when i write something in input field then console.log shows json data with typed value.

Please help.

like image 670
Himanshu Avatar asked Feb 03 '15 11:02

Himanshu


People also ask

What is [( ngModel )] used for?

The ng-model directive binds the value of HTML controls (input, select, text-area) to application data. It is a part of the FormsModule. This directive is used by itself or as part of a larger form. It accepts a domain model as an optional Input.

What is data ng model in AngularJS?

ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form. We can use ngModel with: input.

How do you share data between controller and view?

14) Which of the following is used to share data between controller and view in AngularJS? Answer: B: "using services" is the correct answer.


1 Answers

Well you need to define $scope.saveJson as property within your controller

angular.module('myapp').controller('formDataController', ['$scope',
function($scope){
$scope.saveJson = "something";    
$scope.saveForm = function(){
        console.log($scope.saveJson);
    }
}
]);
like image 87
mindparse Avatar answered Nov 09 '22 04:11

mindparse