简体   繁体   English

指令不起作用angularjs

[英]directive not working angularjs

The directive does not work from the controller. 该指令不适用于控制器。 how to fix it? 如何解决?

baseapp.directive('loading', function () {
    alert('loading');
    return {
        restrict: 'E',
        replace: true,
        template: '<div class="loading">loading</div>',
        link: function (scope, element, attr) {
            scope.$watch('loading', function (val) {
                if (val) {
                    element.addClass('show');
                    alert('show');
                } else {
                    element.addClass('hide');
                    alert('hide');
                }
            });
        }
    }
});

baseapp.controller ('ListCtrl', function ($scope, $http) {
    $scope.loading = true;
    $http.get('/blog').success(function(data) {
        $scope.users = data;
        $scope.loading = false;
    });
});

When you load a directive called. 加载指令时。 from the controller $ scope.loading = true; 从控制器$ scope.loading = true; Nothing happens 什么都没发生

If you read the official documentation: https://docs.angularjs.org/guide/directive 如果您阅读了官方文档: https : //docs.angularjs.org/guide/directive

You can read this: 您可以阅读以下内容:

The restrict option is typically set to: 限制选项通常设置为:
'A' - only matches attribute name 'A'-仅匹配属性名称
'E' - only matches element name 'E'-仅匹配元素名称
'C' - only matches class name 'C'-仅匹配类别名称

If you want to use it as a class like you do, then you have to specify : 如果要像使用类一样将其用作类,则必须指定:

require: 'C'

What I noticed is that your adding a class over and over element.addClass('show'); 我注意到的是,您在element.addClass('show');之上添加了一个类element.addClass('show'); resulting in if true and later false: class='show hide show hide ...' and so forth, one quick way to correct this is to remove one of the classes or you can toggle class: 导致if为true,以后为false: class='show hide show hide ...'等等,一种更正此问题的快速方法是删除其中一个类,或者您可以切换类:

 .directive('myDir', function() {
      return {
        restrict: 'E',
        replace: true,
        template: '<div class="loading">loading</div>',
        link: function (scope, element, attr) {
            scope.$watch('loading', function (val) {
                if (val===true) {
                    element.addClass('show');
                     element.removeClass('hide');
                } else {
                    element.toggleClass('hide');
                    element.removeClass('show');
                }
            });
        }
    }
    });

Other than that it seems to be working just fine on my end: 除此之外,它在我看来似乎还不错:

Online Demo 在线演示

Note : I recommend you not to use alerts for debugging use console.log instead. 注意 :建议您不要使用警报进行调试,而应使用console.log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM