0

input field:

<input  type="text" data-ng-model="some_model" />

The initial state of some_model is null. When I add some arbitrary value to the input field and remove it again, some_model becomes an empty string.

What I can do to solve this is something like:

if($scope.some_model != null && $scope.some_model != undefined && $scope.some_model.trim() == 0){
      $scope.some_model=null;
  }

This works, but I'm wondering if there is a standard angular way of doing this?

MeesterPatat
  • 2,671
  • 9
  • 31
  • 54
  • In your controller do you have the model set? You might/could have a default on the model. – alphapilgrim May 27 '16 at 14:06
  • The model is retrieved from the backend in the controller. So if it's value was null in the db, it will get a default value of null. And if I don't change it, it should stay null, but this is not what is happening in the scenario described. – MeesterPatat May 27 '16 at 14:09
  • http://stackoverflow.com/questions/25344368/angular-ng-model-empty-strings-should-be-null – Alexander Kravets May 27 '16 at 15:05

1 Answers1

0

I created this pen to work from, seem to be getting the expected null value. Will update as needed. Feel Free to fork and plug in some of your code.

angular
  .module('app', [])
  .controller('ExampleController', ExampleController)
  .factory('exampleService', exampleService);
ExampleController.$inject = ['$timeout'];

function ExampleController($timeout) {
  var vm = this;
  vm.text = null;
  activate();

  function activate() {
    $timeout(function() {
      if (vm.text != null && vm.text != undefined && vm.text.trim() == 0) {
        vm.text = null;
      }
      console.log(vm.text);

    }, 10);
  }
}

function exampleService() {
  var service = {
    //basic CRUD operations.
    post: post,
    get: get,
    update: update,
    remove: remove
  };
  return service;

  function post() {}

  function get() {}

  function update() {}

  function remove() {}

}
<body ng-app="app">
  <div class="container-fluid" ng-controller="ExampleController as vm">
    <input type="text" ng-model="vm.text" />
  </div>
</body>
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58
  • I'm not sure I understand. You want me to modify the code so that it shows the problem I have? Also I never used codepen, how do I save my changes? – MeesterPatat May 27 '16 at 14:48
  • @MeesterPatat Negative, if there are things in your code mine is missing to better replicate the problem feel free to fork and include a link. – alphapilgrim May 27 '16 at 14:49
  • http://codepen.io/anon/pen/XKWJBz?editors=1010 see the comments above function test. – MeesterPatat May 27 '16 at 14:57