如何将ng-template分配给指令templateUrl字段

时间:2015-07-16 10:21:04

标签: javascript angularjs angular-directive angular-template

这是我的ng-template脚本:

  <script type="text/ng-template" id="temp1.html">
         <div style="min-width: 320px; min-height: 213px; max-width: 320px; max-height: 213px">
          <p style="background-color:black; color:white; margin:20px; padding:20px;">A simple tempalate child</p>
          <div style="background-color:gray; color:white;">Html contents also works ok!!!</div>
          <div>The quick brown fox jumps over the lazy dog</div>
          <p>
            Make the fox
            <button type="button" onclick="alert('Jump!!');">jump</button>
          </p>
        </div>
    </script>

这是我的指令定义:

app.directive('mydiv', function(){
  return {
    restrict: 'E',
    templateUrl: "'temp1.html'",

  }
});

但是我在控制台中收到以下错误:

Error: [$compile:tpload] http://errors.angularjs.org/1.2.21/$compile/tpload?p0='temp1.html'
    at Error (native)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:6:450
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:60:488
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:72:132
    at l.promise.then.w (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:100:39)
    at l.promise.then.w (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:100:39)
    at l.promise.then.w (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:100:39)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:101:295
    at k.$get.k.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:111:373)
    at k.$get.k.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:108:462)(anonymous function) @ angular.js:10023$get @ angular.js:7327l.promise.then.w @ angular.js:11532l.promise.then.w @ angular.js:11529l.promise.then.w @ angular.js:11529(anonymous function) @ angular.js:11662$get.k.$eval @ angular.js:12632$get.k.$digest @ angular.js:12444$get.k.$apply @ angular.js:12736h @ angular.js:8339w @ angular.js:8553A.onreadystatechange @ angular.js:8492

我在将ng-template分配给templateUrl属性的方式上做错了吗?

1 个答案:

答案 0 :(得分:3)

替换:

templateUrl: "'temp1.html'",

使用:

templateUrl: "temp1.html",

您不需要JS变量中的那些额外引号。

DEMO