Angular.js isolated scope directive not working
I am creating an angular directive. I am binding a property to an isolated scope in a 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>
As I type textarea the model is not updated.
What am I missing?
source to share
I don't see how you tie the inner contentModel
to yours textarea
.
Here is an updated working fiddle .
I changed someobj.text.data
to ng-model
on 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}}
to make sure it {{content}}
links in the outer area:
<div ng-app="myapp">
<data-tc-markdown content-model="content"></data-tc-markdown>
{{content}}
</div>
it looks like it works.
source to share
The "content" variable must be defined in the outer scope of your directive. For example, see below: I have defined content1 and content2 in an external controller. They contain the values ββthemselves.
http://jsfiddle.net/jajtzyhh/3/
var myapp = angular.module('myapp',[]).controller('MyController', ['$scope', function($scope) {
$scope.content1 = 'Hello';
$scope.content2 = 'World';
}]);
<div ng-app="myapp">
<div ng-controller="MyController">
<data-tc-markdown content-model="content1"></data-tc-markdown>
<data-tc-markdown content-model="content2"></data-tc-markdown>
</div>
</div>
source to share