【发布时间】:2015-01-21 15:39:29
【问题描述】:
我看到了一个代码示例并进行了编辑以实现我需要的功能。
你可以在http://jsfiddle.net/infnadanada/abr5h5we/看到它
问题是当通过“uiwidget”指令初始化两个(或更多)对象时,这两个对象返回最后传递的值。
有没有办法解决这个问题,或者其他代码允许我使用属性(+ 其他属性,如您所见)将 $templateCache 传递给指令?
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>
角度
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:我是 Angular 新手,很抱歉我的英语不好 :D 谢谢!
【问题讨论】:
标签: javascript angularjs angular-directive angular-template