【问题标题】:Addclass dont work with angular directiveAddclass 不适用于角度指令
【发布时间】:2016-10-03 21:28:11
【问题描述】:
<form name="configurationForm" class="form-horizontal config-form" novalidate confirm-on-exit>

我有这段代码,如果我在输入中添加一个类并且如果我输入不同的值,初始值,它适用于我,但如果我输入:input type = "number",但如果我输入:input type = "text",则不会工作

<input highlight type="text" maxlength="32" ng-pattern="/^[0-9]+(\.[0-9]{1,4})?$/" step="0.0001" class="form-control input-config" name="orifice_size" id="orifice_size" ng-max="model.asset.line_size"ng-model="model.asset.orifice_size"   >

module.directive('highlight', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            ngModel: "="
        },
        link : function($scope, element, attributes, ctrl){
            $scope.$watch('ngModel', function (newVal, oldVal, scope) {
                if (scope.$parent.copyModel !== undefined && scope.$parent.copyModel[element[0].id] !== undefined &&  (newVal !== scope.$parent.copyModel[element[0].id] )) {
                    element.addClass('input-change');
                     console.log(element)
                }
                else{
                    element.removeClass('input-change');
                }
            });
        }

      };
});

【问题讨论】:

  • 这是您的 if 条件的问题,或者您没有向我们展示所有代码。什么是复制模型?你想达到什么目的?
  • @Ronnie 感谢您的回答,如果值不相等,我会在输入、初始值和用户插入的值中添加一个类
  • copyModel 会是什么样子?所以你是在比较两个数字?
  • @Ronnie 是我从表中加载数据,所以我可以得到原始值,我需要比较原始数字,在字段中输入新数字
  • @FERNANDOORTIZ - 考虑使用 ng-class

标签: angularjs angularjs-directive addclass


【解决方案1】:

$scope.$watch() 方法中使用 attributes.$addClass() 代替 element.addClass()

如果您查看 [ng-class] 的 AngularJS 源代码,由于某种原因,他们不使用 element.addClass(),而是使用这种方法。

我不能完全解释为什么这完全有效,但我知道它会专门解决这个问题。

作为参考,这里是 AngularJS 的[ng-class] 的来源:

https://github.com/angular/angular.js/blob/master/src/ng/directive/ngClass.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2020-05-24
    • 2015-01-02
    • 2015-06-12
    相关资源
    最近更新 更多