【问题标题】:angular directive restrict M not work角度指令限制 M 不起作用
【发布时间】:2017-08-31 07:06:52
【问题描述】:

有一个指令将 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>

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案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>

    【讨论】:

    • 有效!谢谢!!!但我只将 'abc' 更改为 '
      abc
      ' 并且 'replace' 属性已在官方文档中被弃用。 :)
    • 'replace' 属性已在官方文档中被弃用,你能分享一下这个信息的来源吗?
    • 我发现 replace 属性是显示评论指令的必要条件,但它也已被弃用。哈哈
    【解决方案2】:

    我对您的代码做了一些小改动,并且效果很好。我在指令中添加了 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>
    

    【讨论】:

    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多