Get ng-model in controller

1,606 views
Skip to first unread message

ru ga

unread,
Mar 25, 2014, 10:57:51 PM3/25/14
to ang...@googlegroups.com
Hi all,

I've built a application with AngularJs and NodeJs, view template EJS.
When I render a page, I set value of input (ng-model) and I want to get that model in controller but I can't get it.
This is my file EJS:

<!DOCTYPE html>
<html ng-app='test'>
    <head>
        <script src="/angular/angular.js"></script>
        <link rel='stylesheet' href='/stylesheets/style.css' />
    </head>
    <body ng-controller='testCtrl'>
        <input type="text" ng-model='testModel' ng-change='change()' ng-init="testModel ='John'">
    </body>
</html>

<script>
    var testApp = angular.module('test', []);

    testApp.controller('testCtrl', function($scope){
        $scope.change = function(){
            console.log($scope.testModel);
        };
        console.log($scope.testModel);
    });
</script>

Anyone can help me please?
Thanks and Best Regards,

ev...@vfiles.com

unread,
Mar 26, 2014, 12:23:04 PM3/26/14
to ang...@googlegroups.com
http://docs.angularjs.org/api/ng/directive/ngChange

"The expression is not evaluated when the value change is coming from the model."

if you want to call change() any time the model changes, just execute a $watch on the model.

$scope.$watch('testModel', $scope.change);

And instead of using ng-init in your template, you should be setting the model in your controller

$scope.testModel = 'John';

Gordon Bockus

unread,
Mar 26, 2014, 10:45:20 PM3/26/14
to ang...@googlegroups.com
removing the ng-init and just populating the scope var in your controller works: 

I went to check out the docs of ngInit and found: http://docs.angularjs.org/api/ng/directive/ngInit
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

So yeah...don't do it that way :).  
No need for the watch when model is tied to a scope property.  
Reply all
Reply to author
Forward
0 new messages