角度指令限制M不起作用

时间:2017-08-31 07:06:53

标签: angularjs angularjs-directive

有一个指令限制M作为后面的代码。但是在页面上没有任何结果。怎么了?谢谢!

<!DOCTYPE html>
<html ng-app="app">
<head>
    <script type="text/javascript" src="lib/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('app',[]);
        app.controller('indexCtrl',function($scope){

        });
        app.directive('di',function(){
            return{
                restrict:"M",
                template:'abc'
            };
        })
    </script>
</head>
<body ng-controller="indexCtrl">
<!-- directive:di -->
</body>

</html>

2 个答案:

答案 0 :(得分:1)

两件事:

  • 模板需要包含在HTML标记中
  • 向指令添加replace: true属性,将自定义di替换为HTML模板

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

});

app.directive('di', function() {
  return {
    restrict: 'M',
    template: '<p>abc</p>',
    replace: true
  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app">

<body ng-controller="indexCtrl">
  <!-- directive:di -->
</body>

</html>

答案 1 :(得分:0)

我对您的代码做了一些小改动,但它确实有效。我在指令中添加了 replace:true ,并将修改后的模板参数添加为 html内容

代码:

<!DOCTYPE html>
<html ng-app="app">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('app',[]);
        app.controller('indexCtrl',function($scope){

       });
        app.directive('di',function(){
            return{
                restrict:"M",
                replace : true,
                template:'<b>abc</b>'
            };
        })
    </script>
</head>
<body ng-controller="indexCtrl">
<!-- directive:di -->
</body>

</html>