10

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.

7
  • you should always set scope variable like $scope.saveJson = saveJson from your controller.setting scope variable outside angular will not run the digest cycle , scope variable will not update..you need to do $scope.$apply() to get updated value of all scope variables Commented Feb 3, 2015 at 12:02
  • how should i use this $scope.$apply() Commented Feb 3, 2015 at 12:33
  • you could use if(!$scope.$$phase) $scope.$apply() but this is bad code in terms of angular.' Commented Feb 3, 2015 at 12:35
  • I used but its not working Commented Feb 3, 2015 at 12:48
  • you should do it before accessing $scope, inside controller Commented Feb 3, 2015 at 12:52

1 Answer 1

3

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);
    }
}
]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.