0

I'm probably missing some key component of Angular rendering and assignment, but I thought when a variable was updated within the scope of a controller, any areas it affects would be re-evaluated. However, it doesn't appear to work in this simple case

var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {
    $scope.name = 'Superhero';

    $scope.specialObject = {
        whoawhat: $scope.name
    }
}

http://jsfiddle.net/ADukg/14138/

I expect the "specialObject.whoawhat" to update when I change "name", and I've tried it with a function as well. How do I trigger an update of the object property?

6
  • Is there a reason that you arent binding to the object directly? Commented Aug 24, 2017 at 21:02
  • Formatting issues, I have to perform some extra functions on the data before it is ready to be stored in that property Commented Aug 24, 2017 at 21:04
  • Couldnt you bind to it directly and then perform the extra functions on the Object? Commented Aug 24, 2017 at 21:05
  • Technically yes, I could call an onChange to fire a function which manipulates the data, but if I was going to do that, I may as well set the variable with the data. Looking to do it without that, if possible. Commented Aug 24, 2017 at 21:07
  • Well your current scenario is trying to bind to the object directly through inheritance which is like binding directly anyway. Making the object update will be no different than binding to it directly. I will provide an answer below. let me know if it meets your needs. Commented Aug 24, 2017 at 21:12

1 Answer 1

1

Here is one example that could make this work.

Code:

<input type="text" ng-model="name" ng-change="update()">

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
   $scope.name = 'Superhero';

   $scope.specialObject = {
       whoawhat: $scope.name
   }

   $scope.update = function(){ //bind this to change

       //do whatever logic you need to do here before updating the object
       $scope.specialObject.whoawhat = $scope.name
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.