0

I have a simple view with an input text field in which the user enter his name and a controller must retrieve that value an assign to employeeDescription variable. The problem is that the ng-model value (from the input) doesn't come to the controller, I just tried using $watch like Radim Köhler explains Cannot get model value in controller method in angular js but doesn't work. I just think it must be simple.

Also a just try by retrieving the name variable (ng-model) from the $scope, like $scope.employeeDescription = $scope.name; but doesn't retrieve value and the Google chrome console doesn't give me any output about that. Any solution?

index.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>

<body ng-app='angularApp'>
    <div ng-controller='nameController'>
        <div>
            Name <input type="text" ng-model='name' />
        </div>

        Welcome {{employeeDescription}}
    </div>

    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

(function(angular) {
    var myAppModule = angular.module('angularApp', []);

    myAppModule.controller('nameController', function($scope) {
        $scope.employeeDescription = name;
    });

})(window.angular);
1
  • you can't 2 way bind primitives. which is why you should always have a dot in ng-model which means you are using an object to bind to Commented Jan 27, 2015 at 18:15

1 Answer 1

1

Your code should fail, cause the 'name' variable in the controller is never defined. You have two variables defined in your code: $scope.employeeDescription and $scope.name (defined in the ng-model of the input). Note that '$scope.name' is being defined, not 'name'.

My suggestion is to leave only one variable:

<div>
    Name <input type="text" ng-model='employeeDescription' />
</div>

myAppModule.controller('nameController', function($scope) {
    $scope.$watch('employeeDescription', function() {
        console.log($scope.employeeDescription);
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

But what about if I want to build a string message with using that variable inside the controller, how can I retrieve that value?
updated the answer with a watcher to check the employeeDescription and do something with it, in this case, log it ;) I'd suggest add an ng-blur to the input and process your string in a function called there, so you edit the string once the user has finnished editing ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.