AngularJS 属性更改列表中的<model>事件/侦听器



那里。我需要一个观察程序或事件,当列表(产品)中保留的模型(Details)上的属性发生更改时,它将被激发。

视图:

<tr class="data-row" data-ng-repeat="c in c.products">
{{c.name}} <-- if c.name changes fire an event
{{c.expire}} <-- if c.expirechanges fire an event
{{[...]}} <-- c contains many properties

ViewModel

c.setDirtyFlag()
{
    c.dirty=true;
}

这个问题有angularjs的解决方案吗?问候

@Shomz我用下面的代码试了一下手表。但是,当属性c.expires将在输入字段中更改时,将不会引发监视。

    $scope.$watch("c.products.expire", function (newValue, oldValue) {
        log.debug(newValue);
    });

编辑:更具体地说:产品列表将在运行时生成。用户还可以添加和删除项目。这个"临时"添加的对象也应该被关注。

您可以在$scope.products数组变量中的每个项上设置$watch,并以这种方式执行事件处理。

_.each(products, function(product) {
    $scope.$watch(function() { return product; }, function(newVal, oldVal) {
        if(newVal.name != oldVal.name || newVal.expire != oldVal.expire || ...) {
            //do event work
            product._isDirty = true;
        }
    });
});

或者,如果您将其包装在一个表单中,您可以检查该表单的$dirty变量以查看是否有。

谢谢你把我带到正确的方向@wbeange。这是我目前的解决方案。$watchlist没有像我预期的那样工作,所以我使用了"旧"的$watch。

$scope.$watch("c.products",
               function (newValue, oldValue) {
                   //first initialising of list
                   if (typeof newValue != 'undefined' && c.products.length > 0) {
                       if (newValue != oldValue && oldValue!=null) {
                           for (var i = 0; i < newValue.length; i++) {
                               if (newValue[i].expire!= oldValue[i].expire
                                   || newValue[i].otherprop != oldValue[i].otherprop)
                               {
                                   //todo
                               }
                           }
                       }
                   }
               },
               true // Object equality (not just reference).
           );

最新更新