JSFiddle - React, Tailwind, and code Playground
by ospatil
HTML
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js'></script>
<script src='//ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular-mocks.js'></script>
<div ng-app='myApp' ng-controller='UpdateThisCtrl'>
<h1>dynamic includes with $watch/$observe in a directive</h1>
<h2>loads, but doesn't change:</h2>
<hr>
<update-this-on-attr-change content='template1'>
</update-this-on-attr-change>
<hr>
<button ng-click='change()'>click me to update attr</button>
</div>
CSS
h1 { font-size: 1.5em; }
h2 { font-size: 1.2em; }
JavaScript
var app = angular.module('myApp', []);
app.directive('updateThisOnAttrChange', ['$http', '$compile',
function(http, compile) {
return {
restrict: 'E',
scope: true,
link: function(scope, elm, attrs) {
var childScope;
scope.$watch(function(){return elm.attr('content');}, function(val) {
scope.include = val + ".html";
});
},
template: '<div ng-include="include"></div>'
}
}]);
function UpdateThisCtrl($scope, $window) {
$scope.change = function() {
var elem = $window.document.getElementsByTagName('update-this-on-attr-change')[0];
var template = 'template2';
angular.element(elem).attr('content', template);
console.log(elem);
}
}
app.config(function($provide) {
$provide.decorator('$httpBackend',
angular.mock.e2e.$httpBackendDecorator);
});
app.run(function($httpBackend) {
$httpBackend.whenGET('template1.html').respond('initial content');
$httpBackend.whenGET('template2.html').respond('switch to this when attr changes');
});