ng-model assign value in html and read and assign in controller $scope
-
21-12-2019 - |
Question
I am a Angular newbie and trying to achieve this,
Assign a ngmodel value in view and read it back in controller to pass it to my service
<input name="item" ng-model="itemId" ng-init="itemId='3'">
In my controller i am accessing it via
@MyDevelopmentApp.controller 'myCtrl',[
'$scope'
($scope) ->
console.log($scope.itemId)
It returning undefined.
How can i return the Id from my view to the controller?
Solution
That code in the controller is being executed before ng-init
. If you wait until it has been parsed, it should work: demo
Edit: You can register a watcher that will be triggered when the value is initialized or when you change the variable afterwards. Updated fiddle with an example.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow