Zerok
Zerok

Reputation: 1503

Input value not showing up (AngularJS)

I've got this controller:

app.controller('controlFormulario', function($scope) {
  this.formulario = [];
  this.formulario.fecha = new Date();
});

...this directive:

app.directive('formulario', [function() {
  return {
    restrict: 'E', // C: class, E: element, M: comments, A: attributes
    templateUrl: 'modules/formulario.html'

  };

... and this view:

<div class="form-group">
  <label for="fecha">Fecha</label>
  <input type="fecha" class="form-control" id="fecha" ng-model="fecha" value="{{formCtrl.formulario.fecha | date}}"  disabled>
</div>

As you may guess, the attribute value has the date, perfectly filtered and so. No problem here. The actual problem comes when you see the website, and find out that the input doesn't show up anything. The "value" attribute is perfectly assigned, but it's not showing it inside the input box.

Why? Am I doing something wrong? Tried the same with ng-init, ng-value... I'm a newbye on AngularJS, just ended the basic tutorial and I'm trying to practise and get some more knowledge, so maybe I'm missing out something.

Any help?

Upvotes: 0

Views: 2154

Answers (2)

Razvan B.
Razvan B.

Reputation: 6771

As a best practice, you shouldn't use $scope, instead, like you did, you should use controllerAs, so, in your controller:

var cf = this;

and then, instead of using

this.formulario = []; 
this.formulario.fecha = new Date();

you should have

cf.formulario = [];
cf.fetcha = new Date();

then, in your html, you would have

ng-controller="controlFormulario as cf"

Then, the input model becomes: cf.fetcha and all other scopes from the controller should now be prefixed with cf.

<input type="fecha" class="form-control" id="fecha" ng-model="cf.fecha" value="{{formCtrl.formulario.fecha | date}}"  disabled>

Here is a good Article that better explains this

Upvotes: 1

cbeeson
cbeeson

Reputation: 76

You need to store the data attribute to the $scope.

Check out this link: https://docs.angularjs.org/guide/scope

Upvotes: 1

Related Questions