AngularJs具有一个指令的多个模板视图

时间:2015-01-21 15:39:30

标签: javascript angularjs angular-directive angular-template

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

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

中看到它

问题是当用“uiwidget”指令初始化两个(或更多)对象时,两个对象返回传递的最后一个值。

有没有办法解决这个问题,或者其他允许我使用属性传递给指令$ templateCache的代码(+你可以看到的其他attrs)?

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谢谢!

1 个答案:

答案 0 :(得分:0)

只需添加范围:true到yr指令......

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

相关问题