AngularJs:自定义指令的动态模板不替换属性值

时间:2015-04-27 08:45:23

标签: javascript angularjs angularjs-directive

我认为这一行:

<html lang="en" ng-app="localjhourlad">

.....

<ng-carousel-item 
   title="AngularJS custom directive's title attribute"
   content="I am a custom attribute, as well!"
   thumbnail="/img/logo.png">
</ng-carousel-item>

在我的app.js文件中:

var ngApp = angular.module("localjhourlad", ['ngRoute']);

ngApp
    .config(['$interpolateProvider',
        function ($interpolateProvider) {
            $interpolateProvider.startSymbol('[[');
            $interpolateProvider.endSymbol(']]');
    }]);

//Custom Directives
ngApp
    .directive('ngCarouselItem', function() {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="item">' +
                      '<div style="background-image: url([[thumbnail]])">' +
                      '<div class="carousel-caption">' +
                      '<h3>[[title]]</h3>' +
                      '<p class="hidden-sm hidden-xs">[[content]]</p>' +
                      '</div>' +
                      '</div>' +
                      '</div>'
        }
    });

一切都按预期工作,因为我看到自定义指令元素被指令的模板替换,只有表达式绑定没有被属性值替换,即:

<div class="item" 
   title="AngularJS custom directive's title attribute" 
   content="I am a custom attribute, as well!"      
   thumbnail="/img/logo.png">

   <div style="background-image: url()">
      <div class="carousel-caption">
         <h3 class="ng-binding"></h3>
         <p class="hidden-sm hidden-xs ng-binding"></p>
      </div>
   </div>
</div>

我现在没有想法。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

尝试添加&#34;范围&#34;在Directive Defn Object中

ngApp
    .directive('ngCarouselItem', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
              thumbnail: "@",
              title: "@",
              content: "@"
            }
            template: '<div class="item">' +
                      '<div ng-style="background-image: url([[thumbnail]])">' +
                      '<div class="carousel-caption">' +
                      '<h3>[[title]]</h3>' +
                      '<p class="hidden-sm hidden-xs">[[content]]</p>' +
                      '</div>' +
                      '</div>' +
                      '</div>'
        }
    });

答案 1 :(得分:0)

您未在指令中声明范围,这意味着您正在使用父级的范围。但是在该范围内,thumbnail/title/content不是范围上的变量,而是DOM元素的属性。

您有两个选择:

声明隔离范围,如下所示:

scope: {
      thumbnail: "@",
      title: "@",
      content: "@"
}

然后保持HTML原样,或者:

链接功能中添加范围

link: function(scope, element, attr) {
    scope.thumbnail = attr.thumbnail;
    scope.title = attr.title;
    scope.content = attr.content;
}