I am working on my first 'proper' AngularJS project and have encountered a problem when using a transcluded directive within my controller. In overview, I want my transcluded directive to 'wrap' some form elements in my view. Here is the simplified code...
(function () {
angular.module('testApp', [])
.directive('xyzFieldSet', function () {
return {
template: '<fieldset ng-transclude></fieldset>',
restrict: 'E',
transclude: true
};
})
.controller('testCtrl', ['$scope', function($scope) {
$scope.name = 'Fred';
$scope.changedName = '';
$scope.nameChanged = function() {
$scope.changedName = $scope.name;
};
}]);
}());
and the corresponding HTML...
<div ng-app="testApp">
<div ng-controller="testCtrl">
<h2>Without 'fieldset' directive</h2>
<p>The 'Changed Name' field changes as the 'Name' is changed.</p>
<p>Name: <input ng-model="name" ng-change="nameChanged()" /></p>
<p>Changed Name: {{ changedName }}</p>
</div>
<hr />
<div ng-controller="testCtrl">
<h2>With 'fieldset' directive</h2>
<p>
With the transcluded directive 'wrapping' the content,
the 'Changed Name' field <em>does not</em> change as
the 'Name' is changed.
</p>
<xyz-field-set>
<p>Name: <input ng-model="name" ng-change="nameChanged()" /></p>
<p>Changed Name: {{ changedName }}</p>
</xyz-field-set>
</div>
</div>
Without the transcluded directive, any changes to the input field are correctly bound to scope, however, when I add the transcluded directive, the data binding does not work.
A fiddle demonstrating the problem can be found at https://jsfiddle.net/tgspwo73/1/
From what I have read, I am guessing that the directive is changing the scope of its child elements. If this is the case, is there a way of circumventing this behaviour?