Angular: Why Won't Model Update Outside Of View In Same Controller?

402 views Asked by At

I have found a number of posts talking about models/views not updating, but I still can't figure this out. I'm new to Angular, btw so I suspect this is noob issue.

I have the below Angular app.

When the text input test_var is edited, the edited value isn't updated in the sidebar, but it is in the view. Why and how do I fix it?

This works when I don't use views and routes.

I've tried a sidebar controller, but no difference. I've tried $rootScope, which partially worked (it broke other functionality), but I'd prefer not to use a global scope.

Thanks for taking a look.


HTML

<body>

 <div ng-app="rxApp" ng-controller="WizardCtrl">
  
  <div class="ng-view">
  </div>

  <div class="sidebar">
   <span ng-bind="test_var"></span>
  </div>

 </div>

</body>

View (One.html)

<input ng-model="test_var" />
 
<span ng-bind="test_var"></span>

Controller

rxApp.controller( 'WizardCtrl', function ( $scope, $http, $routeParams, $location, FileUploader ) {

   $scope.test_var = 'please work!';

)};

Routes

rxApp.config(['$routeProvider',
 function($routeProvider) {
  $routeProvider.
  when('/one', {
   templateUrl: 'templates/one.html',
   controller: 'WizardCtrl'
  }).
  when('/two', {
   templateUrl: 'templates/two.html',
   controller: 'WizardCtrl'
  }).
  otherwise({
   redirectTo: '/one'
  });
 }
]);

2

There are 2 answers

5
AndroConsis On BEST ANSWER

Controllers are disposed when transmuting routes. As for Best Practice you should create a Service to handle that data. You should not use controllers to carry data between views. In your case, the problem is Controllers are disposed when transmuting routes.

See the angular docs on how to use controllers correctly. http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

2
Amit Sirohiya On

The problem is the making of model variables.

You have to have a dot in model. Make your model point to an object.

So in your controller do like this -

rxApp.controller('WizardCtrl',function($scope, $http, $routeParams,$location, FileUploader){

    $scope.test ={
         var : 'please work!'
       };

)};

View (One.html)

<input ng-model="test.var" />

<span ng-bind="test.var"></span>

HTML

<body>

    <div ng-app="rxApp" ng-controller="WizardCtrl">

        <div class="ng-view">
        </div>

        <div class="sidebar">
            <span ng-bind="test.var"></span>
        </div>

    </div>

</body>

To read more about scope go through this UnderStanding Scopes