2 Example(s) of angular extend


Description :

angular.extend creates a shallow copy of one or more sources object provided to destination object. In this example three objects students, student1 and student2 source object students and dest as destination object. See the code snippet:


angular extend Example - 1
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Welcome in the AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="extendController">
        <div ng-repeat="extStudent in dest">
            {{extStudent.name}}
        </div>
    </div>
<script>
    var app = angular.module("app", []);
    app.controller('extendController', ['$scope', function ($scope) {
        $scope.students = [{ name: 'Herry', id: 1 }, { name: 'John', id: 2 }, { name: 'Peter', id: 3 }];
        $scope.students1 = [{ name: "test", cls: "MCA" }];
        $scope.students2 = [{ name: 'A', id: 1 }, { name: 'B', id: 2 }, { name: 'C', id: 3 }];
        $scope.dest = {};
        angular.extend($scope.dest, $scope.students, $scope.students1, $scope.students2);
    }]);
    </script>
</body>
</html>

Output

Description :

In this example of angular extend two source object will be copied to destination object one object is created by user and another is already in code and show both combine obj in UI in text box.


angular extend Example - 2
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Welcome in the AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="app">
    <div ng-controller="extendController">
        First Name: <input type="text" ng-model="user.txt1" /><br />
        Last Name: <input type="text" ng-model="user.txt2" /><br />
        <button ng-click="chngVal()">Extend</button><br />
        First Name: <input type="text" ng-model="extnd.txt1" /><br />
        Last Name: <input type="text" ng-model="extnd.txt2" /><br />
        <div ng-repeat="ex in extnd">
            Name: <input type="text" ng-model="ex.name" /><br />
            Age: <input type="text" ng-model="ex.Age" /><br />
        </div>
    </div>
</body>
</html>
<script>
    var app = angular.module("app", []);
    app.controller('extendController', ['$scope', function ($scope) {
        $scope.extnd = [{}];
        $scope.chngVal = function () {
            var tempObj = [{ name: "Abc", Age: "27" }, { name: "Xyz", Age: "30" }]
            angular.extend($scope.extnd, $scope.user, tempObj);
        }
    }]);
  
</script>

Output