Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js directive isolated scope not working

I am building a angular directive. I am binding a property to isolated scope in directive like

scope : {
   contentModel : '='
}

'use strict';

/**
 * Tc markdown directive
 */
var myapp = angular.module('myapp',[]);

myapp.directive('tcMarkdown',[function() {
  var directive = {};
  directive.restrict = 'E';
    directive.template = '<div><div class="row"><!--Content edit pane --><div class="col-md-12"><textarea class="form-control editor" ng-model="someobj.text.data"></textarea></div></div></div>{{contentModel}}';
  directive.scope = {
    contentModel : '='
  };

  directive.link = function(scope, element, attrs) {
    scope.options = {selected : 0};
    scope.$watch(function() {
      return scope.options.selected;
    }, function(newVal) {
      if(newVal===1) {
        scope.buttonCaption = {text : 'Edit'};
      } else if(newVal === 0) {
        scope.buttonCaption = {text : 'Preview'};
      }
    });
  };
  return directive;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<data-tc-markdown content-model="content"></data-tc-markdown>
</div>
The two way binding is not working.

As I am typing in textarea the model is not updated.

What am I missing ?

like image 435
Syed Avatar asked Mar 28 '26 18:03

Syed


1 Answers

I don't see how you are binding the internal contentModel to your textarea.

Here is an updated working fiddle.

I replaced the someobj.text.data assigned to ng-model with contentModel:

  myapp.directive('tcMarkdown',[function() {
  var directive = {};
  directive.restrict = 'E';
    directive.template = '<div><div class="row"><!--Content edit pane --><div class="col-md-12"><textarea class="form-control editor" ng-model="contentModel"></textarea></div></div></div>';
  directive.scope = {
    contentModel : '='
  };

  directive.link = function(scope, element, attrs) {
    scope.options = {selected : 0};
    scope.$watch(function() {
      return scope.options.selected;
    }, function(newVal) {
      if(newVal===1) {
        scope.buttonCaption = {text : 'Edit'};
      } else if(newVal === 0) {
        scope.buttonCaption = {text : 'Preview'};
      }
    });
  };
  return directive;
}]);

And then I pulled {{contentModel}} out to make sure that {{content}} binds in the outer scope:

<div ng-app="myapp">
<data-tc-markdown content-model="content"></data-tc-markdown>
    {{content}}
</div>

this seems to work.

like image 157
Davin Tryon Avatar answered Apr 01 '26 08:04

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!