How to bind to event.time variable in parent scope from a directive with isolate scope without using $parent in directive?

37 views Asked by At

angular.module('hfp.calendar')
    .controller('printPreviewCntrl', ['$scope', 'htmlFromServer',
     function($scope, htmlFromServer){

         $scope.htmlReceived = htmlFromServer;
            $scope.event = {};

}])
.directive('compile', function($compile, $timeout) {

    return {
     restrict: 'A',
  link: function(scope, element, attrs) {
   $timeout(function() {
    element.html(scope.$eval(attrs.compile));
    $compile(element.contents())(scope);
   });
  }
 };

})
.directive('initModel', function($compile) {

 return {
  restrict: 'A',
  scope: {
   eventField: '=initModel'
  },
  link: function(scope, element, attrs) {
   scope.eventField = element[0].innerText;
   element.attr('ng-bind', '$parent.' + attrs.initModel); // why do i have to use $parent here to make it work ?
   element.removeAttr('init-model');
   $compile(element)(scope);
  }
 };

});
<!-- clientside html -->
<input type="text" ng-model="event.time">
<div compile="htmlReceived">

</div>

<!-- html coming from server -->
<div init-model="event.time">
 10:30 AM
</div>

I want to bind to the parent scope var event.time from initModel directive but it only works when i use $parent to refer to the var in parent scope. Can i achieve this binding without using $parent ?

1

There are 1 answers

2
georgeawg On

There is no need to implement that directive with isolate scope. Simply use the $parse service:

angular.module("app",[])
.directive('initModel', function($parse) {
    return {
        restrict: 'A',
        //scope: {
        // eventField: '=initModel'
        //},
        link: function(scope, elem, attrs) {
            var setter = $parse(attrs.initModel).assign;
            setter(scope, elem.text().trim());
            scope.$watch(attrs.initModel, function(value) {
                elem.text(value);
            });
        }        
     };
})
<script src="//unpkg.com/angular/angular.js"></script>

<body ng-app="app" ng-init="event={}">
    <input type="text" ng-model="event.time">
    <div init-model="event.time">
        10:30 AM
    </div>
</body>

For more information, see AngularJS $parse Service API Reference.