2

I have a very little piece of code to test some things I can do with Angular, and obviously nothing can work when you do so. Here is the html (correctly connected to angular and the script file, I'm sure of that, since previous tests worked and the console is not throwing any error): HTML:

<div ng-controller='greet'>
    <p>Welcome {{first}}<span id='name' ng-click='addUserName()' title='click to change name'>{{userName}}</span>! This is the <span id='number' ng-click='resetNumber()' ng-attr-title='if you ask, it {{isPrimeNumberView}} a prime number. Click to reset'>{{number}}</span> time you visit the main page</p>
  </div>

JS:

if(!localStorage.number){
    localStorage.number=1;
}else{
    ++localStorage.number;
}
if(!localStorage.userName){
    localStorage.userName='[click]';
}
function greet($scope){
    function addUserName(){
        localStorage.userName=prompt('Name?');
        $scope.userName=localStorage.userName;
        $scope.$apply();
    }
    function resetNumber(){
        localStorage.number=0;
        $scope.number=0;
        $scope.$apply();
    }
    if(localStorage.first){
        $scope.first='back ';
    }else{
        localStorage.first=true;
    }
    $scope.number=localStorage.number;
    $scope.userName=localStorage.userName;
    $scope.isPrimeNumberView='IS';
    var n=localStorage.number;
    if(n==1){$scope.isPrimeNumberView='is not';}
    for(var i=2; i<=Math.sqrt(n); ++i){
        if(n%i==0){$scope.isPrimeNumberView='is not'; i=n;}
    }
}

If you try and change your name it doesn't update it until you reload the page, and if you click the numbers to reset them it doesn't show that until you reload the page too. That is not tipical of Angular: can someone tell me what I did wrong?

1 Answer 1

4

Your click event handlers run outside of Angular's digest cycle. You need to call $scope.$apply() after changing the values. Use ngClick to bind your handlers if you want it to work automatically.

And also, your functions should be declared as a method of the scope object. For example: function resetNumber() should be $scope.resetNumber = function()

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

3 Comments

I tried to do it as you said and documented a bit on ng-click and apply(), but still can't work. I modified the post with the changes you told me... I surely did something wrong, can you find out what plz?
what do you mean by that? They're functions declared in the greet function, and if you mean that they should have the scope parameter they should inherit it from the previous function... what do you mean?
Needs to be something like $scope.addUserName = function () { ... };

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.