2015-09-24 75 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