javascript - An array value is changed in negative value even if i am not performing any operation on it -


i assigned $scope.option value in tmp variable , perform operation on tmp variable after value of $scope.option changed negative values.

var app = angular.module('myapp', []);  app.controller('myctrl', function($scope) {        $scope.options=[1,2,3];        var tmp = $scope.options;         for(var i=0;i<tmp.length;i++){      tmp[i] = tmp[i]*-1;    }        console.log($scope.options);        document.getelementbyid("p1").innerhtml = $scope.options;            });
<!doctype html>  <html>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>  <body>    <div ng-app="myapp" ng-controller="myctrl">    <p id="p1"></p>    </div>  </body>  </html>

instead of copying values var tmp = $scope.options;, use angular.copy().

var app = angular.module('myapp', []);  app.controller('myctrl', function($scope) {        $scope.options=[1,2,3];        var tmp = angular.copy($scope.options);         for(var i=0;i<tmp.length;i++){      tmp[i] = tmp[i]*-1;    }        console.log($scope.options);       });
<!doctype html>  <html>  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>  <body>    <div ng-app="myapp" ng-controller="myctrl">    <p ng-repeat="option in options">{{ option }}</p>    </div>  </body>  </html>


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -