0

I have a view like so:

<div ng-controller= "test" ng-init = "doit()">
    <span>{{testval}}</span>
</div>

The view's controller looks like this:

function test($scope){
    var counter = 0;
    $scope.doit = function(){
       console.log('switched to view');
       $scope.testval = counter++; 
    };
};

The first time I switch to the view controlled by 'test', it shows '0'. After that, it shows nothing, but the console.log continues firing. How can I set this up to execute 'doit' each time I switch to the view and successfully update the view by modifying $scope?

Thanks

2 Answers 2

5

Remove the ng-init() and put the call to doit() into your controller:

function test($scope){
    var counter = 0;
    $scope.doit = function(){
       console.log('switched to view');
       $scope.testval = counter++; 
    };
    $scope.doit();
};

Each time you switch to this view, the controller code will execute. If you want the counter to persist between view changes, you'll have to put it into a service or $rootScope (because the controller, well its $scope, is destroyed when you move to another view).

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

2 Comments

I thought the controller was instantiated as an object? I want to be able to call "doit" dynamically and on-the-fly from within the view.
@Andrew, when ng-controller is encountered in the HTML (or when ng-view is used and a route specifies which controller to create for that route, and you switch to that route) Angular creates a new scope and then "applies (in the sense of JavaScript's Function#apply) the controller constructor function" to the new scope object. So is there also a controller object? It is not clear to me if there is or not.
0

Had to add $scope.digest() to the end of doit. The example listed is a boiled down example of the logic I was encountering on a much smaller scale. In reality, it was a function called getPhysOrd that executed an asynchronous templated websocket bridge to query data off the server. It had to be able to do this on-the-fly. Calling digest forced the watchers to update the view according to the model changes. Thanks

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.