Organiccat
Organiccat

Reputation: 5651

Updating object property in angular with dynamic variable

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?

Upvotes: 0

Views: 472

Answers (1)

Ohjay44
Ohjay44

Reputation: 897

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
   }
}

Upvotes: 1

Related Questions