2

I'm trying to $watch for a change on a model within a ui-bootstrap accordion. Binding works within the view, but when the model changes, the $watch doesn't fire.

http://plnkr.co/edit/DcoGT2?p=preview

How do I get the value of $scope.myModel in the controller?

user2570109
  • 23
  • 1
  • 3

1 Answers1

7

Use an object rather than a primitive:

<div ng-controller="AccordionDemoCtrl">
  <accordion>
    <accordion-group heading="Static Header">
      <input ng-model="model.myModel"> {{ model.myModel }}
    </accordion-group>
  </accordion>
</div>

angular.module('plunker', ['ui.bootstrap']);
function AccordionDemoCtrl($scope) {
  $scope.model = {myModel: ''};
  $scope.$watch('model.myModel',function(){
    console.log($scope.model.myModel);
  })
}

Plunker

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • This just fixed an issue for me - but can someone point me to an explanation of why a primitive doesn't work here? – henry May 29 '14 at 09:32
  • 1
    @henry, probably because the accordion-group directive creates a child scope, so the child gets a copy, not a reference. For more info see http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs – Mark Rajcok Jun 05 '14 at 02:53