2015-09-24 71 views
1

用下面的代码提示:比较对象的属性,改变元素类/如果不同

public class Person { 
    private Long id; 
    private String name; 
    private List<Dog> dogs; 
} 

public class Dog { 
    private Long id; 
    private Long oldId; 
    private Long age; 
} 

我个人的两个对象,“人”和“editedPerson”。我想比较两者,如果一个属性不同,请更改元素的类并创建一个工具提示,以显示另一个对象属性的值。而且我希望能够在ng-repeat中做到这一点,根据其id/oldId比较人员列表中的Dog属性(比较ng-repeat内的狗与具有与dog ID相同的oldID的狗)

这是怎么我到目前为止做的一个例子:

<b ng-class="{ 'different' : person.name != editedPerson.name)}" 
tooltip="{{(person.name != editedPerson.name) ? 'New: ' + editedPerson.name : ''}}"> 
Name:</b> 
<p>{{person.name}}</p> 

的问题是,我要的属性很多,其中一些是不同类型的内部列表。该sollution我对名单至今为每个属性创建一个功能,例如

compareDogAge = function(dog, dogs) { 
    // Foreach on dogs until dogs[i].oldId == dog.id, return true if age is equal 
} 

我想知道如果我要保持我目前的解决方案,或设法使/找到一个指令,可以解决我的问题(我在制定指令方面的经验很少)。

在此先感谢

编辑

我用下面的函数来了这么远,但还没有测试它尚未

equals = function(fieldName, originalObj, newObj) { 
    if (newObj instanceof Array) { 
     for (var i = 0; i < newObj.length; i++) { 
      if (originalObj.id == newObj[i].oldId) { 
       return originalObj[fieldName] == newObj[i][fieldName]; 
      } 
     } 
    } else if (newObj instanceof Object){ 
     return originalObj[fieldName] == newObj[fieldName]; 
    } 
} 

我仍然认为一个指令会更好

回答

1

Angular有一个等于函数,是不是你想要的?

https://docs.angularjs.org/api/ng/function/angular.equals

angular.equals(person, editedPerson); 

编辑

一个指令做这个逻辑添加到您分量应该是这样的:

的Html

<div ng-app="myApp"> 
    <div class="myDir"> 
     <span different old-value='foo' new-value='bar'>FooBar</span> 
    </div> 
</div> 

var app = angular.module("myApp", []).directive('different', function() { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs){ 

      //Add your logic to check the differences here 
      //You can use the function you already have 
      if (attrs.oldValue !== attrs.newValue){ 

       //Do other stuff you want to do with the element here 
       element.addClass('different');     
      } 

     } 
    } 
}); 

小提琴:http://jsfiddle.net/marcosspn/8ucakhk5/

+0

我刚才看到你想知道什么属性是不同的。在这种情况下,我的回答将无济于事。 – marcosspn