【问题标题】:AngularJs multiple template views with one directiveAngularJs 一个指令的多个模板视图
【发布时间】: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


    【解决方案1】:

    只需将 scope: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));                
                    });    
              }
            } 
        }
    }]);
    

    在此处了解有关范围的更多信息:https://github.com/angular/angular.js/wiki/Understanding-Scopes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2017-02-06
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多