0

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.

6
  • Why do you need it as a function? Can't you directly declare it as a scope variable? Commented Jul 10, 2016 at 7:25
  • 1
    You can't edit it because every time angular evaluates the expression, a new object is created. That does make much sense. Create the object once, and store the object in the scope. Commented Jul 10, 2016 at 7:26
  • @Chinni - I need to dynamically decide which is correct object for binding - either locate an existing object in some data structure or initialize a new one. Commented Jul 10, 2016 at 7:35
  • @JBNizet - It does make a lot of sense (and I'd be happy to accept it as the answer if you'll post it). So in your opinion - a good way to achieve this will be to use ng-init to dynamically decide on the object and then a simple expression in ng-model? Commented Jul 10, 2016 at 7:37
  • No. As documented, ng-init should almost never be used. Just put the code creating the object in the controller. Commented Jul 10, 2016 at 7:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.