angularjs模板不显示

时间:2017-07-11 21:07:15

标签: angularjs

我使用角度js制作了一个基本的自定义指令。我可以将范围记录到控制台,但它不会在标记内显示模板。我正在摆弄继承,共享和隔离的范围,并想知道我的指令是否错误嵌套?



var myApp = angular.module('myApp', []);
    myApp.controller('StudentController', ['$scope', function ($scope) {

    $scope.student = {
        name: "dj",
        age: 32,
        subject: [
            "math",
            "geography"
        ]
    }
 
    $scope.setGrade = function (student) {
        student.grade = "A+"
    }
        //console.log($scope.student);
              myApp.directive('studentDir',function(){
            
           return{
               template:"{{student.age}} years old!",
               replace: true,
               restrict: 'E',
               controller: function($scope){
                   //console.log($scope);
               }
           } 
        });
 
}]);
        
        
  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<body ng-app="myApp">

    <div ng-controller="StudentController">
   
    <student-dir></student-dir>

    
    
    
    </div>
      
    </body>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

从指令中删除replace: true将使其正常工作。因为当您使用replace: true时(虽然已经弃用),您必须在template中单个DOM元素,因为$compile服务只需要单个根来编译。但是这里有{{student.age}} years old!个DOM节点。

Demo 1

或者使用span / div

等元素包装器包装模板内容
template:"<span>{{student.age}} years old!</span>",

Demo 2

答案 1 :(得分:0)

另一种解决方案是使用<div>

包装模板
return {
    template:"<div>{{student.age}} years old!</div>",
    replace: true,
    restrict: 'E',
    controller: function($scope){
        //console.log($scope);
    }
} 

修改

如果您的代码与上面发布的代码相同,那么您需要在控制器之外声明您的指令,如下所示:

var myApp = angular.module('myApp', []);
myApp.controller('StudentController', ['$scope', function ($scope) {

    $scope.student = {
        name: "dj",
        age: 32,
        subject: [
           "math",
           "geography"
        ]
    }

    $scope.setGrade = function (student) {
        student.grade = "A+"
    }

}]);

myApp.directive('studentDir',function(){
    return{
        template:"<div>{{student.age}} years old!</div>",
        replace: true,
        restrict: 'E',
        controller: function($scope){
            //console.log($scope);
        }
    } 
});