javascript - DOM 元素未从 Angular Controller 更新

标签 javascript html angularjs dom

我正在尝试在 ng-blur 上运行一个函数,该函数将根据为该字段定义的正则表达式 验证用户输入。

我想要实现的是,如果正则表达式与用户输入不匹配,我想将特定文本字段输入框边框变为红色。

我知道这是一个简单的 JavaScript 案例,我们使用 getElementById() 并修改 DOM。我无法从常规 Controller 更新 DOM。

我无法使用 ng-messages 等,因为我想根据正则表达式失败的情况从 Controller 抛出错误,因此我无法编写硬编码的 ng-messages

任何有关如何进一步进行的见解都会非常有帮助。

代码: prop 对象:这将从 salesforce 服务器检索。我提供了解释代码所需的要点。实际响应需要大量预处理,才能在运行时生成包含所有引用、查找字段、从服务器拉取的选项列表选项等的表单。

[ 
 { label      : Application Name
   cid        : uniqueId
   typeApex   : CURRENCY
   fieldPath  : application_Name__c
   type       : NUMBER
   value      : ''
   dbRequired : true
   isRequired : false
 },
 {...similar array of JSON object ...},
 {}
]

查看.html

<div ng-if="prop.type != 'picklist' && prop.type != 'reference'">
    <label for="{{prop.label}}">{{prop.label}}</label>
    <input type="{{prop.type}}" id="inputFields{!cid}" ng-blur='fieldValidation(prop.fieldPath, prop.typeApex, inputFields{!cid}, $event)' ng-model-options="{updateOn: 'blur'}"  
           class="form-control" name="{{prop.fieldPath}}" ng-model="fieldPathValue[prop.fieldPath]" ng-init="fieldPathValue[prop.fieldPath]=getDefaultValue(prop.type,prop.value)"
           ng-required="isRequired({{prop.dbRequired}}, {{prop.isRequired}})"/>
</div>

Controller :

从这里我尝试更新错误时输入文本框的 DOM 元素

$scope.fieldValidation = function(fieldPath, type, id, $event) {

   // Hardcoded regular expression for testing, this will be read  from server object
    var myMap = new Map();
    myMap.set("Term__c","^[0-9]+$");
    myMap.set("Loan_Amount__c","[0-9]+(\.[0-9][0-9]?)?");

    var value = $event.target.value; //$event object contains element Id, user input value
    var reg = new RegExp(myMap.get(fieldPath));

    if(!reg.test(value)) {
       //add error message class to selected field
       //display error message on top of field

       $timeout(function(){
         // added $scope.apply recently, not a good practice I understand 
         $scope.$apply(function () {
           $scope.spanId = document.getElementById($event.srcElement.id);
           $scope.spanId.style.borderColor='#ff0000';
           $scope.spanId.style.border='solid';
           }); 
         }, 1000);
        }

最佳答案

首先,不需要在 $timeout 内使用 $apply,因为它在内部使用它。最佳实践,Dom 操作不应存在于 Controller 、服务或其他任何地方,而应存在于指令中。

.directive('fieldvalidate', [
  function() {
    return {
      restrict: 'A',
      link: function($scope, $element, $attributes) {
        $element[0].onblur = function() {
          //check against regex
          if(){//if failed
            $element[0].style.borderColor='red';
            $element[0].insertAdjacentHTML('afterend', '<div>your message</div>');
          }
        }
      }
    };
  }
]);

关于javascript - DOM 元素未从 Angular Controller 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894762/

相关文章:

javascript - MD 数组 : Add additional array if value isn't found

javascript - React Typescript 映射循环接口(interface)错误

javascript - 需要一种方法来设置我无法访问的元素的样式

html - 具有 flexbox 属性的布局

javascript - AngularJS:ng-pattern 检查整数输入

angularjs - 如何从 Angular 1x 中的嵌套子组件调用父组件中的函数

javascript - JS : Specifying current element in the menu

javascript - 定义边框宽度(不是厚度)

javascript - 根据单选按钮选择向日期添加值

javascript - Angular UI-Router 在具有 go 函数的状态之间传递数据不起作用