0

I'm having trouble with what I though would be a rather pedestrian use case. Given the following form

<form class="form-inline" role="form">
  <div class="form-group">
    <input type="text" ng-model="customerInput" size="80" class="form-control" placeholder="Type the company name here"/>
    <button class="btn btn-primary" ng-click="addCustomer(customerInput)">Add</button>
  </div>
</form>

I simply want to clear the input field after adding the customer.

  $scope.addCustomer = function(customer) {
    $scope.customers.push({name: customer});
    $scope.customerInput = '';
  }

It doesn't work, so I inspected the $scope. The customerInput value I'm looking for lives in the $scope.$$childHead. This works.

  $scope.addCustomer = function(customer) {
    $scope.customers.push({name: customer});
    $scope.$$childHead.customerInput = '';
  }

I'm clearly doing something wrong. Can someone shed some light?

andyczerwonka
  • 4,230
  • 5
  • 34
  • 57
  • http://stackoverflow.com/questions/17606936/angularjs-dot-in-ng-model – Blackhole Apr 27 '14 at 19:43
  • With more testing, it only works when I turn off caching in devtools. Nevertheless, the value that I type in the form seems to be in the wrong `$scope`. – andyczerwonka Apr 27 '14 at 19:44
  • see http://jsfiddle.net/49KLd/ – Nitish Kumar Apr 27 '14 at 19:44
  • @Blackhole is correct. It's something with another scope being injected because of the way I'm dynamically routing a submenu. I want to use one controller for two admin pages and that is creating the problem. – andyczerwonka Apr 27 '14 at 19:54

1 Answers1

0

Angular $scopes often do things that you don't expect because of the inheritance chain. For this reason, it's useful to define a Plain Old JavaScript var and reference that within the scope:

angular.module('myApp').controller(function ($scope) {
    var model = {
        customerInput: ''
    };

    $scope.model = model;
});

And then in your template: <input ng-model="model.customerInput" />. Now you can operate on the model var in functions of that $scope, and be confident that only your chosen $scope is operating on that model. Of course, as you get more familiar with $scope inheritance patterns, you'll often want the implicit sharing between Controllers. And of course, in such a case, you could also store the data on a service.

user128268
  • 126
  • 1