how in angularjs we can achieve the object update which is based on some other objects?

Samir Shah

I am trying to update values of variables b and c with an add method (simply incrementing their value) but a (the sum of the two) is not reflecting this operation.

I understand we can use a $scope.$watch function to update them, but I have an application with many objects dependent on other objects. If my dependent object changes I want my object to also changes without using any $watchers.

This is just a simple example where I am trying to get $scope.a and $scope.obj.a value updated with the help of watchers. How do I do this?

<html ng-app="app">
  <head>
    <title></title>
  </head>
  <body ng-controller="ctrl">
    a : {{a}}<br />
    b: {{b}}<br />
    c: {{c}}<br />
    <button ng-click="add();">Add</button>
    <br /><br /><br />

    obj.a : {{obj.a}}<br />
    obj.b: {{obj.b}}<br />
    obj.c: {{obj.c}}<br />
    <button ng-click="obj.add();">obj.Add</button>

    <script type="text/javascript" src="angular.min.js"></script>
    <script>
        var app = angular.module('app', []);
        app.controller('ctrl', function ($scope) {
            $scope.b = 1;
            $scope.c = 2;
            $scope.a = $scope.b + $scope.c;


            $scope.$watch('b', function (newValue, oldValue) {
                $scope.a = $scope.b + $scope.c;
            });
            $scope.add = function () {
                $scope.b++;
                $scope.c++;
            };

            //this is object with dot property example
            $scope.obj = {};
            $scope.obj.b = 1;
            $scope.obj.c = 2;

            $scope.obj.a = $scope.obj.b + $scope.obj.c;


            $scope.$watch('obj.b', function (newValue, oldValue) {
                $scope.obj.a = $scope.obj.b + $scope.obj.c;
            });
            $scope.obj.add = function () {
                $scope.obj.b++;
                $scope.obj.c++;
            };
        });
    </script>
  </body>
</html>
Christina

You can achieve this by declaring a (or obj.a respectively) as a function instead of an object / object property. The function will automatically by re-executed by Angular each time any of the properties it uses change and therefore your "a" values will change without the need for you to explicitly define the watches.

See your updated code below:

 var app = angular.module('app', []);
        app.controller('ctrl', function ($scope) {
            $scope.b = 1;
            $scope.c = 2;
            $scope.a = function() {return $scope.b + $scope.c};        
            $scope.add = function () {
                $scope.b++;
                $scope.c++;
            };

            //this is object with dot property example
            $scope.obj = {};
            $scope.obj.b = 1;
            $scope.obj.c = 2;
            $scope.obj.a = function() {
              return $scope.obj.b + $scope.obj.c;
            }


            $scope.obj.add = function () {
                $scope.obj.b++;
                $scope.obj.c++;
            };
        });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">
  <head>
    <title></title>
  </head>
  <body ng-controller="ctrl">
    a : {{a()}}<br />
    b: {{b}}<br />
    c: {{c}}<br />
    <button ng-click="add();">Add</button>
    <br /><br /><br />

    obj.a : {{obj.a()}}<br />
    obj.b: {{obj.b}}<br />
    obj.c: {{obj.c}}<br />
    <button ng-click="obj.add();">obj.Add</button>
  </body>
</html>

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

How to bind a list of objects of a class to a datagridview whose one field is again an object of some other class?

분류에서Dev

how is Array object different from other objects

분류에서Dev

Do we have a limit number of interfaces which we can impliment to an object? (in Java)

분류에서Dev

GSON is deprecated. Which one we can use to serialize and deserialize Java objects to and from JSON?

분류에서Dev

How to "connect" objects in 2 classes to make them update each other?

분류에서Dev

Using AutoMapper to create an object, which represents a result of comparing two other objects

분류에서Dev

Loop over a reference object multiple times to copy its properties to other objects in Javascript/Angularjs

분류에서Dev

How to find docs with arrays in which elements match some other element in another array?

분류에서Dev

Vue.js: How can I update an array of objects?

분류에서Dev

How we can make EditText with thick border(some color) and with white background in android?

분류에서Dev

Angularjs: call other scope which in iframe

분류에서Dev

How can I sort this object by 'sortby' key which inside an array?

분류에서Dev

angularjs object changes affects other object

분류에서Dev

How could patch method in Rails update only some attributes while the other attributes are blank?

분류에서Dev

How can one object instance stop sound that other instance is playing?

분류에서Dev

How can I flatten this object stream without creating duplicate objects?

분류에서Dev

How can we transform pairwise mapped strings to multiple groups of strings based on a score?

분류에서Dev

How can I use jquery .grep() to find an object then update it?

분류에서Dev

How can I achieve this tab style in android?

분류에서Dev

if we apply some properties in both html and css code which one will apply first and which will be finally applied

분류에서Dev

Can we dynamically create an object by checking existance?

분류에서Dev

Can we emplace small object on void*?

분류에서Dev

How can I set a worksheet object based on a worksheet's codename?

분류에서Dev

NSPredicate SUBQUERY for object composed of arrays of other objects

분류에서Dev

Based on the following MYSQL query how can I write an UPDATE statement to update a value?

분류에서Dev

Selenium/Java How can I pass desired capabilities to FireFoxDriver, when its already taking in some other parameters?

분류에서Dev

How can you delete a array of pointers which points to a dynamically allocated objects

분류에서Dev

In C++, how can I tell WHICH piece of code is allocating what TYPE of objects?

분류에서Dev

Which android activity should hold objects used by other activites?

Related 관련 기사

  1. 1

    How to bind a list of objects of a class to a datagridview whose one field is again an object of some other class?

  2. 2

    how is Array object different from other objects

  3. 3

    Do we have a limit number of interfaces which we can impliment to an object? (in Java)

  4. 4

    GSON is deprecated. Which one we can use to serialize and deserialize Java objects to and from JSON?

  5. 5

    How to "connect" objects in 2 classes to make them update each other?

  6. 6

    Using AutoMapper to create an object, which represents a result of comparing two other objects

  7. 7

    Loop over a reference object multiple times to copy its properties to other objects in Javascript/Angularjs

  8. 8

    How to find docs with arrays in which elements match some other element in another array?

  9. 9

    Vue.js: How can I update an array of objects?

  10. 10

    How we can make EditText with thick border(some color) and with white background in android?

  11. 11

    Angularjs: call other scope which in iframe

  12. 12

    How can I sort this object by 'sortby' key which inside an array?

  13. 13

    angularjs object changes affects other object

  14. 14

    How could patch method in Rails update only some attributes while the other attributes are blank?

  15. 15

    How can one object instance stop sound that other instance is playing?

  16. 16

    How can I flatten this object stream without creating duplicate objects?

  17. 17

    How can we transform pairwise mapped strings to multiple groups of strings based on a score?

  18. 18

    How can I use jquery .grep() to find an object then update it?

  19. 19

    How can I achieve this tab style in android?

  20. 20

    if we apply some properties in both html and css code which one will apply first and which will be finally applied

  21. 21

    Can we dynamically create an object by checking existance?

  22. 22

    Can we emplace small object on void*?

  23. 23

    How can I set a worksheet object based on a worksheet's codename?

  24. 24

    NSPredicate SUBQUERY for object composed of arrays of other objects

  25. 25

    Based on the following MYSQL query how can I write an UPDATE statement to update a value?

  26. 26

    Selenium/Java How can I pass desired capabilities to FireFoxDriver, when its already taking in some other parameters?

  27. 27

    How can you delete a array of pointers which points to a dynamically allocated objects

  28. 28

    In C++, how can I tell WHICH piece of code is allocating what TYPE of objects?

  29. 29

    Which android activity should hold objects used by other activites?

뜨겁다태그

보관