I have a series of templates in a dropdown bound to $scope.templates:
[{"id":1, "name":"Test 1",{"id":2, "name":"Test 2"}]
.
I also have a directive,
<editor data-template="1"></editor>
Depending on the template selected in the dropdown, it should re-render the directive with the appropriate template. Is this possible? To date I've only seen simple one-to-one databinding of fields to divs, and nothing triggering a re-render of an entire directive. What is the best approach for this situation?
Update: Even more basic to the directive $scope, is cross-controller two-way binding. e.g. I can't seem to figure out how to keep a service object in sync across Controllers. What I'd really like to happen is for the changes in one controller to be available to the other controller and vice versa. http://jsfiddle.net/9gSVn/1/
One way is to create a directive that replaces the html contents when a scope value changes. This blog post is very helpful in describing the steps to create a directive with dynamic templates.
Here is a sample fiddle with a directive that watches for model changes:
module.directive('template', function () {
var getTemplate = function (id) {
var template = '<div>no template for ' + id + '</div>';
switch (id) {
case 1:
template = '<div>template 1 from directive</div>';
break;
case 2:
template = '<div>template 2 also from directive</div>';
break;
}
return template;
}
return {
restrict: 'E',
replace: true,
scope: { id: '=templateId' },
link: function (scope, element, attrs) {
scope.$watch('id', function (newValue, oldValue) {
element.html(getTemplate(newValue));
});
}
};
});