Controller does not see ng-model of Angular JS

Asked

Viewed 1,179 times

0

The Create ctrl controller is not seeing the ng-model input of my form. I can pass values from the controller to the view but I’m not getting the reverse. Where am I going wrong?

Controller:

    .controller('CriarCtrl', function ($scope) {
    $scope.criarDemanda = function () {
        console.log($scope.name);
    }
})

View:

<input type="text" ng-model="name" name="nome" required />
<button class="button button-assertive button-block activated" ng-click="criarDemanda()">Enviar</button>
  • Try to do that: ng-click="criarDemanda(name)" and on your controller: $scope.criarDemanda = function (name) and then console.log(name)

  • I understood but I have 20 inputs and I want to send all ng-models to the controller at the click of the button. It would be correct to send an array with all?

  • The ideal is to have an object with all the properties. So the way @Techies said you would pass only the object "person".

2 answers

3

Try sending an object.

ng-click="demanda.name"

If you have more attributes that enter this demand just follow this pattern, example:

ng-click="demanda.quantidade"

Then just pass the demand to the method called in ng-click:

 ng-click="criarDemanda(demanda)

I tried to find a way to answer that question of yours and if I explain it in the way I "understand" it might confuse you.

Take a look here: http://tableless.com.br/criando-uma-aplicacao-simples-com-angularjs/

And if it is good of English of a look at the documentation of the Angular.

  • You solved it. That’s exactly what it was. Thank you. But the question remains: Why doesn’t the controller see the ng-model input? Can anyone explain?

  • Take a look here: https://jsfiddle.net/joshdmiller/HB7LU/ see that an example similar to your code also works. Controller sees your view and vice versa

1

The ngModel directive is responsible for linking an input, select, textarea, and other controls to a property in Scope, without the need to pass such information as arguments to any method.

For more information see https://docs.angularjs.org/api/ng/directive/ngModel

Follow example working correctly.

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div id="entityScope" ng-app="myApp" ng-controller="CriarCtrl">
    <input type="text" ng-model="name" name="nome" required />
    <button ng-click="criarDemanda()">Enviar</button>
</div>    
<script>
var app = angular.module('myApp', []);
app.controller('CriarCtrl', function ($scope) {
    $scope.criarDemanda = function () {
        console.log($scope.name);
    }
});
</script>

</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.