I saw an example of code and edited to fulfill the functions I require.
You can see it in http://jsfiddle.net/infnadanada/abr5h5we/
The problem is that when initialize two (or more) objects by "uiwidget" directive the two objects return the last value passed.
Is there any way to fix this, or other code that allows me to pass to the directive a $templateCache using attributes (+ other attrs as you can see)?
HTML
<div ng-controller='MainCtrl'>
<uiwidget template="templates.button" class="btn btn-primary" text="asdt"></uiwidget>
<uiwidget template="templates.button" class="btn btn-danger" text="yooo"></uiwidget>
</div>
ANGULAR
var myApp = angular.module('myApp',[]);
myApp.run(function($templateCache) {
$templateCache.put('button', '<button class="{{class}}">{{text}}</button>');
});
myApp.controller('MainCtrl', function($scope, $timeout) {
$scope.templates =
{
button: 'button'
};
});
myApp.directive("uiwidget", ["$compile", '$http', '$templateCache', function ($compile, $http, $templateCache) {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.text = attrs.text;
scope.class = attrs.class;
scope.$watch(attrs.template, function (value) {
if (value) {
loadTemplate(value);
}
});
function loadTemplate(template) {
$http.get(template, { cache: $templateCache })
.success(function(templateContent) {
element.replaceWith($compile(templateContent)(scope));
});
}
}
}
}]);
PD: I'm new with Angular and sorry for my bad English :D Thanks!
Just add scope:true to yr directive...
myApp.directive("uiwidget", ["$compile", '$http', '$templateCache', function ($compile, $http, $templateCache) {
return {
restrict: 'E',
scope:true,
link: function(scope, element, attrs) {
scope.text = attrs.text;
scope.class = attrs.class;
scope.$watch(attrs.template, function (value) {
if (value) {
loadTemplate(value);
}
});
function loadTemplate(template) {
$http.get(template, { cache: $templateCache })
.success(function(templateContent) {
element.replaceWith($compile(templateContent)(scope));
});
}
}
}
}]);
Read more about Scope here : https://github.com/angular/angular.js/wiki/Understanding-Scopes