Search code examples
angularjsangularjs-scope

Angular - binding a dynamically created object


I'm using Angular and I can't edit a dynamically created object, even though it is presented correctly (meaning the binding works).

I have the following view:

<html>
  <head>
  </head>
  <body ng-app='TestApp'>
    <div ng-controller='TestCtrl'>
      <input ng-model="newModel().name"/>
    </div>
  </body>
</html>

And the following controller implementation:

    var TestApp = angular.module("TestApp", []);

    function TestCtrl($scope) {
      $scope.newModel = function(){
        return { name: 'Fresh' }    
      }
    }

I'm using a method to return the correct object for binding because I need to execute some logic to decide which object should be binded. The input field displays the correct, dynamically created, value. But I cant seem to edit it.

What am I doing wrong? Is this the wrong way to achieve such a functionality?

Thanks.


Solution

  • Instead of returning an object and by attaching a function to the scope, you can update a scope variable in the function.

    Controller code:

    var TestApp = angular.module("TestApp", []);
    
    function TestCtrl($scope) {
        $scope.newModel = {}; // initialize the scope variable
        function updateScope () {
            // do some logic
            $scope.newModel = { name: 'Fresh' }; // update it with the required object
        }
    
        updateScope(); // run the function
    }
    

    HTML code:

    <body ng-app='TestApp'>
        <div ng-controller='TestCtrl'>
            <!-- remove `()` since `newModel` is no longer a function -->
            <input ng-model="newModel.name"/>
        </div>
    </body>
    

    Hope this solves the issue.