1

I've created a directive which creates a div-wrapper around some content using ngTransclude. See this very simple example: http://jsfiddle.net/DHzrr/1/

If you remove the group element from HTML

<div ng-controller="TodoCtrl">
  <form ng-submit="addTodo()">
    <input type="checkbox" ng-model="checked">
  </form>
  <div ng-hide="checked">NOT CHECKED</div>
</div>

the "ng-hide" listener is working. So my group-directive swallows the event emit or isolates the $scope. How can I make this work?

I thought a new scope is only created when using the scope:true attribute in the directive definition object.

Christof Aenderl
  • 4,233
  • 3
  • 37
  • 48

1 Answers1

2

transclude: true creates a new child scope that prototypically inherits from the parent (TodoCtrl) scope. You can solve the problem in one of three ways:

  1. (recommended) bind to an object property defined on the parent scope: ng-model="obj.checked" and in your controller: $scope.obj = {checked: false}
    fiddle
  2. use ng-model="$parent.checked"
  3. use a function to update the model on the parent: add ng-change="toggle()" to your input, then define a function on your controller: $scope.toggle = function() { $scope.checked = !$scope.checked }

See also What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section directives item "4. transclude: true"

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • Thanks for that. Now I've found all the other threads about this topic and your excellent explanations. Think I understand it now. But I'm not 100% lucky because ideally I don't want to change controller nor model and the directives should only add "layout wrappers". Seams not as easy as I thought. – Christof Aenderl Mar 20 '13 at 09:00
  • 1
    @chrise, "best practice" (according to [Misko](http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m)) is to use references in your $scopes to your models. So before you get too far along in your architecture, you might want to revisit that. Then it should be easier for your directives to add the layout wrappers. – Mark Rajcok Mar 20 '13 at 14:27