AngularJs 使用一个指令的多个模板视图

AngularJs multiple template views with one directive

我看到了一个代码示例并进行了编辑以实现我需要的功能。

你可以在http://jsfiddle.net/infnadanada/abr5h5we/

中看到它

问题是,当通过 "uiwidget" 指令初始化两个(或更多)对象时,两个对象 return 传递了最后一个值。

有什么方法可以解决这个问题,或者有其他代码可以让我使用属性(+您可以看到的其他属性)将 $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>

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:我是 Angular 的新手,抱歉我的英语不好 :D 谢谢!

只需将 scope:true 添加到您的指令中...

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));                
                });    
          }
        } 
    }
}]);

在此处阅读有关 Scope 的更多信息:https://github.com/angular/angular.js/wiki/Understanding-Scopes