角度指令不起作用

时间:2016-08-31 10:37:32

标签: angularjs

**Hello.html**

通过制作指令我想做的HTML代码

<script src="angular.min.js"></script>
<script src="world.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

<body ng-app="myApp">

<record></record>
</body>

**world.js**

我只是制定了一个指令,但它没有用,任何人都可以找出我的错误

var app = angular.module("myApp", []);

app.directive("rec",function()
{
    return{
        restrict:'E',
        templateUrl:'record.html',
        controller:function($scope) {
         $scope.records = [
                {
                "Name" : "Alfreds Futterkiste",
                "Country" : "Germany"
                 }, {
                "Name" : "Berglunds snabbköp",
                "Country" : "Sweden"
                 },{
                "Name" : "Centro comercial Moctezuma",
                "Country" : "Mexico"
                },{
                "Name" : "Ernst Handel",
                "Country" : "Austria"
                }
        ],controllerAs:'records'
    }
    };
});

**record.html**

这是一个新的文件record.html,我分隔我的工作负载,但chrome没有显示它。你可以找出我的错误纠正

<table  border="1">
<tr ng-repeat="x in records">
  <td>{{x.Name}}</td>
  <td>{{x.Country}}</td>
</tr>
</table>

2 个答案:

答案 0 :(得分:0)

您的指令名称错误,应该是record而不是rec

app.directive("record",function() {...});

因此它匹配元素<record></record>。 Angular正试图找到<rec></rec>

答案 1 :(得分:0)

controllerAs位于controller内,应该在下面

var app = angular.module("myApp", []);

app.directive("rec",function()
{
    return{
        restrict:'E',
        templateUrl:'record.html',
        controller:function($scope) {
             $scope.records = [
             {
                "Name" : "Alfreds Futterkiste",
                "Country" : "Germany"
             }, {
            "Name" : "Berglunds snabbköp",
            "Country" : "Sweden"
             },{
            "Name" : "Centro comercial Moctezuma",
            "Country" : "Mexico"
            },{
            "Name" : "Ernst Handel",
            "Country" : "Austria"
            }
           ]},
        /*this should be outside of controller*/
        controllerAs:'records'
    };
});

并且您在html中的指令调用必须是指令名称

<rec></rec>

见工作plunker