Angularjs Foreign Key updates
HTML
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="update" ng-controller="homeCtrl">
<input type="text" ng-model="product.name" />
<input type="text" ng-model="option.value" />
<button ng-click="addOption()">Add</button>
<div ng-repeat="option in options|filter:filterOptions" />
<input ng-model="option.value" />
<button ng-click="removeOption(option.id)">Remove</button>
</div>
<button ng-click="updateProduct()">Update Product</button>
</div>
JavaScript
var app = angular.module('update', []);
app.controller('homeCtrl', function($scope) {
$scope.options = [
{
"id": 1,
"opt_type": 1,
"value": "red"
},
{
"id": 2,
"opt_type": 1,
"value": "green"
},
{
"id": 3,
"opt_type": 2,
"value": "4x4"
},
{
"id": 4,
"opt_type": 1,
"value": "blue"
}
];
$scope.option = {
"id": 5,
"opt_type": 1,
"value": ""
};
$scope.product = {
"id": 23,
"options": [1,4],
"name": "Argyle Socks"
};
$scope.optionsCopy = angular.copy($scope.options);
$scope.productCopy = angular.copy($scope.product);
$scope.filterOptions = function(option) {
if ($scope.product.options.indexOf(option.id) !== -1) {
return option;
}
};
$scope.addOption = function() {
$scope.options.push($scope.option);
$scope.product.options.push(5);
$scope.option = {};
};
$scope.removeOption = function(id) {
var index = $scope.product.options.indexOf(id);
$scope.product.options.splice(index, 1);
};
$scope.updateProduct = function() {
for (var i = 0; i < $scope.options.length; i++) {
if ($scope.options[i].value !== $scope.optionsCopy[i].value) {
alert("Option Changed");
}
}
if ($scope.product.options.sort().toString() !==
$scope.productCopy.options.sort().toString())
{
alert("Product Changed");
}
if ($scope.product.name !== $scope.productCopy.name) {
alert("Product Changed");
}
};
});