user3800799 user3800799 - 5 months ago 18
AngularJS Question

Angular transcluded directive - can't access a model thats inside of it

This is my directive code:

'use strict';

demo.directive('myModal', function($parse) {
return {
restrict: 'A',
transclude: true,
scope: '@',
template: '<div ng-transclude><h4>Please enter value</h4></div>'
}
});


Usage is as follows:

<!-- myModal directive -->
<div my-modal>
<input type="text" ng-model="myTest" />
<input type="button" ng-click="getMyTest()" value="Get Value" />
</div>


And my main controller, which wraps the whole application, includes this:

demo.controller('MainCtrl', function($scope) {

$scope.getMyTest = function(){
alert($scope.myTest);
}

});


Any ideas why can't I access
myTest?


JsFiddle: http://jsfiddle.net/sZZEt/679/

Answer

You should use the dot-notation:

demo.controller('MainCtrl', function($scope) {
    $scope.data = {};

    $scope.getMyTest = function(){
    alert($scope.data.myTest);
  }
});

and

<div my-modal>
  <input type="text" ng-model="data.myTest" />
  <input type="button" ng-click="getMyTest()" value="Get Value" />
</div>

JSFIDDLE

Transclusion creates a child scope, that's why you should use the dot-notation for ng-model.

Comments