javascript - Angularjs-我们如何通过动态ng-model名称以及任何更改过滤元素值来观察ng Repeat中的动态元素?

标签 javascript angularjs

我把头撞在水泥枕头上,试图找出动态含量。我不仅可以观看或观察动态内容,而且可以在任何输入上实际使用动态指令。这是一个示例案例...

<tbody>
  <tr ng-repeat="(rowIndex, tableRow) in paymentData.lineItems" ng-hide='false' ng-class="{ paymentrow:  markedForPay[rowIndex] == true }">
    <td>Other td's</td>

    <td class="table-row row-gray">
      <input type="text" class="someClass" placeholder='$0.00' ng-model="tableRow.amount" />
    </td>
  </tr>
</tbody>



在加载时或任何时候,我们都不知道每个输入的ng模型名称。
当用户在每个输入中键入或在每个输入中删除时,我们不容易将所有输入进行汇总。
我们希望有许多用ng-repeat创建的输入字段,因此,只要用户键入任何输入的付款金额td,就可以对它们进行汇总。


像“嘿表,您能给我每一行的值吗?而且,您可以用某种方式存储它们以便我知道它们与哪一行相关吗?哦,我将只需要最新的值。

因此,如果输入包含.34,并且用户删除了这四个,则我需要立即进行新更改,或对任何付款金额输入进行任何更改。

最佳答案

我是Angularjs的新手。如果我刚刚创建的东西已经存在于Angularjs中,请拥抱一下。 (我确实知道有一个针对货币的Angular预置过滤器)。
对于这么多的写作,我并不表示歉意,我更希望您拥有自己实现所需的一切。或至少改善我刚刚提供的代码。

我把头撞在水泥枕头上,试图找出动态含量。我不仅可以观看或观察动态内容,而且还可以使用动态指令来实际使用任何输入。这是一个示例案例...

<tbody>
  <tr ng-repeat="(rowIndex, tableRow) in paymentData.lineItems" ng-hide='false' ng-class="{ paymentrow:  markedForPay[rowIndex] == true }">

    <td class="table-row row-gray">
      <input type="text" watch-dynamic-input="{ index: {{ rowIndex }}, name: 'accountsTableAmountValues', filter: 'usCurrency'}" class="someClass" placeholder='$0.00' ng-model="tableRow.amount" />
    </td>
  </tr>
</tbody>


我希望看到任何变化的任何数量的输入。在这个例子中,我可以求和
特定标题下每行输入的值:或通过添加angularjs的任何输入
元素指令:类型为“ A”。

我从一开始就不会知道型号名称,并且每个输入都可能会进一步嵌入其中
ngRepeat:就是这种情况,但是由于与本示例无关,因此我没有在此表中包含其他嵌套的ngRepeats。实际上,您仅获得此示例的一个输入。

最初,我只是为视图值创建了一个动态过滤器。我没有dbl curlies {{}}使用此过滤器类型{{money | usCurrency}},因为每个输入都不使用{{}}。

我不想在当前指令中塞满一堆逻辑,试图弄清楚每个模型的名称是什么,然后尝试使用$ watch函数将其绑定。所以我首先想到了...

一个动态过滤器指令,用于“可能”任何HTML元素(仅在表单输入中经过测试和使用)。

这是我要用作参考的过滤器...

.filter('usCurrency', [function () {
  return function (amount) {
    amount = amount.toString().replace(/\D/g, '');
    if(amount.length <= 0){
      return amount.replace(/.+/, '');
    }else{
      if(amount.length == 1){
        return amount.replace(/^/, '$ ').replace(/(\d{1})$/, '.$1');
      }else{
        return amount.replace(/^/, '$ ').replace(/(\d{2})$/, '.$1');
      }
    }
  };
}])


这是如上所述的HTML,但是为了清楚起见,仅输入元素...

<input type="text" filterElement='usCurrency' class="anyClass" placeholder='$0.00' ng-model="tableRow.amount" />


这是动态指令,它仅过滤任何输入更改并将最新值添加到ngModel和实际的HTML视图元素(在本例中为实际的输入单元格)。如你看到的

app.directive('filterElement', ['$filter', function($filter){

  return {
    restrict:'A', // Declares an Attributes Directive.
    require: '?ngModel', // ? gets parent scope if it exists.

    link: function( scope, elem, attrs, ngModel ){
      if( !ngModel ){ return };

      scope.$watch(attrs.ngModel, function(value){
        if( value == undefined ){ return };
        ngModel.$setViewValue($filter( attrs.rsFilterElement )( value )); // Sets ngModelView and ngViewValue
        attrs.$$element[0].value = $filter( attrs.rsFilterElement )( value ); // I would prefer to not have to do this step. Any ideas?
      });
    }
  }
}]);


因此,现在只需将filterElement ='yourfilternamecasesensativeasstring'添加到任何输入,就可以对任何动态输入模型进行任何更改,并设置新的ngModel值和所查看的元素。如果您的用例要求更改,则仅对元素值而不对ngModel进行过滤,就可以更进一步,只过滤其中一个。 <-我尚未彻底测试此语句,但是ngModel.value与$$ element [0] .value不同是有道理的,因为该指令要求同时更改ngModel值和元素值。

但是,这并不能满足我要做的另一件事:将表的所有输入加到ANY上或更改其特定输入。我需要一个可以随时通过多个功能访问的控制器变量。因此,我选择执行以下示例,该示例基于以上所有代码。我将只提供带有更改的代码。

首先在控制器中创建对象文字:

$scope.accountsTableAmountValues = {};


该对象将包含所有包含“ A”类型指令的HTML元素。

这是使用指令的HTML以及一些要传递和利用的项目。

<input type="text" watch-dynamic-input="{index: {{ rowIndex }}, name: 'accountsTableAmountValues', filter: 'usCurrency'}" ng-change='selected_to_pay(rowIndex)' class="table-text-field-white payment-field-font-color" placeholder='$0.00' ng-model="tableRow.amount" />


首先,我们通过添加将指令引入动态创建的输入

watch-dynamic-input="index: ng-repeat index number, name: this is the variable name you created in the controller, without the leading $scope, and as string, filter: this can either be a filter name as a string and case sensitive, or just NULL if you don't want to use a filter here.


我们首先通过创建{{rowIndex}}添加ng-repeat的索引。如果仅使用不带花括号的rowIndex,则将为每个输入创建第一个索引号。通过在此处使用curl,rowIndex成为ng-repeat的每个实例,并在每一行的索引上添加广告。

然后,我们只需添加在控制器中创建的对象的字符串名称,在本例中为对象,如果您还记得是'$ scope.accountsTableAmountValues = {};'我们只需要键作为字符串,它就变成... name:'accountsTableAmountValues'。

现在,由于我们正在监视每个输入,因此我们也可以进行过滤,而不是添加上面展示的第一个指令:“ filterElement”。我们只是在过滤器的末尾添加过滤器名称... filter:'usCurrency',或者如果您不想包括过滤器,则只需添加null。

所以这 :

watch-dynamic-input="{index: {{ rowIndex }}, name: 'accountsTableAmountValues', filter: 'usCurrency'}"


使用这个:

app.directive('watchDynamicInput', ['$filter', function($filter){

  return {
    restrict:'A', // Declares an Attributes Directive.
    require: '?ngModel', // ? makes looking for controller on parent element.

    link: function( scope, elem, attrs, ngModel ){
      if( !ngModel ){ return }; // If there is no ngModel, then forget everthing else, and just return.  This may be redundant and better off in the $watch function. Haven't tested yet.

      scope.$watch(attrs.ngModel, function(value){
      // Above, let's watch THIS ROW's ng-model="tableRow.amount"; whatever that value might be.  We don't care now because it's all dynamic, upon page render will be undefined at first, then whatever the user types or deletes.  Who cares!!!  

      if( value == undefined ){ return };  // if you are not yet defined, then return.  I'll catch you on the next input change and check again.  It's OK, we are best friends.  

      // We make a local for improved readability, and faster code.
      // Also, the below code transforms our passed in string of: 
      // "{index: {{ rowIndex }}, name: 'accountsTableAmountValues', filter: 'usCurrency'}"
      // into an actual object literal thus becomes...
      // {index: {{ rowIndex }}, name: 'accountsTableAmountValues', filter: 'usCurrency'}

      var passed_object = scope.$eval(attrs['watchDynamicInput'])

      // and now this works passed_object.index or passed_object.name

      // We allow dynamic filters, or we don't-a as a NULL can be passed into HTML || a filter name
      value = passed_object.filter ? $filter(passed_object.filter)(value) : value;

      // We set the THIS model value to new value (filtered or not, whatever: we're easy like that)
      ngModel.$setViewValue(value);

      // We have to set the element value as well or the filter amount will not display in input
      // I think I am strong arming this.  I just want the ACTUAL element value to match the ngModel.
      attrs.$$element[0].value = value; 

      // Now we just add the new value to our object literal we created in the controller.
      // It will always create a key if nothing is in the object, or it will write over the current value.  If you require ALL inputs old and new you could rewrite and use an array.

      scope[passed_object.name][passed_object.index] = value;

      // This object would now look something like {0: 'row0inputvalue', 1: 'row1inputvalue' etc...}
    });
  }
}


}]);

现在,我只看我想要的任何指令中的对象,在本例中为$ scope.accountsTableAmountValues。在这种情况下,我在下面添加了该对象的示例。

scope.$watch('accountsTableAmountValues', function(amounts){
// You can do what you want now.  I iterate of amounts and sum the values
// and then transfer the result to my $scope.grandTotal in my controller.
// Now I have a way of ALWAYS summing the total on ANY input change to payment amount column inputs
// that were created without knowing the ng-model name or how many there may be.  

}, true); // The true setting here checks the new version to the old version. I need this for my example, but you may not.  


如果您有其他添加,请告诉我。或改进。我们一直在学习我的朋友。

关于javascript - Angularjs-我们如何通过动态ng-model名称以及任何更改过滤元素值来观察ng Repeat中的动态元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25857177/

相关文章:

javascript - 使用map函数解码带有数字数组的字符串

javascript - 使用 Nuxt JS/Firebase 的 Vuex 未知操作

javascript - XMLHttpRequest - JS 无法在被调用的页面上工作

javascript - Angular $route.reload() 没有重新加载 Controller

javascript - AngularJS 上的链接按钮操作

javascript - AngularJs - 临时注入(inject)?

javascript - ajax 请求中没有 'Access-Control-Allow-Origin',但不是通过单击 <a> 标记链接

javascript - React-Redux 删除 HTTP 请求

javascript - 从 Rest API 响应内容配置输出 [Object, Object] 下载 javascript 中的 excel 文件

javascript - AngularJs Jasmine 无法在 $rootScope 方法中调用 $scope 方法