0

I have an angular app with two controllers, posts and ctrl. I also use ng-if to hide/show a couple of elements.

The Ctrl-controller sets the value $scope.age to true, If I set age=true in the Posts-controller, ng-if-things get triggered, now they won't get triggered until I reload the page. Why not and what should I do about it?

<body ng-controller="Posts">
    <div class="age red" ng-if="!(age)">
        <form ng-submit="submit()" ng-controller="Ctrl">
            <div class="pair">
                <label for="yes">Ja, jag har fyllt 20 år</label>
                <input name="yes" type="checkbox" required>
            </div>
            <input type="submit" value="Gå vidare">
        </form>
    </div>
    <div ng-if="age">
            <form class="quiz" ng-class="input"> <label class="first">Dofta på glöggen. Hur doftar Blossa 13?</label>
                ...
            </form>
        </div>

        <section class="{{post.type}}" ng-repeat="post in posts">
           ...
        </section>
    </div>
</body>

Javascript

function Posts($scope, $http) {

    $http.get('/getposts')
    .success(function(data, status, headers, config) {
        $scope.posts = data;
    })
    .error(function(){
        console.log('ajax failed');
    });

    $scope.age = localStorage.getItem('age');
}
function Ctrl($scope) {
    $scope.submit = function() {
        localStorage.setItem('age', true);
        $scope.age = true;
        console.log($scope.age);
    };
}
1
  • Ctrl is a terrible name for a controller Commented Jul 13, 2016 at 13:32

1 Answer 1

1

ngController directive creates a new scope, which inherits from the parent scope. Your inner ngController declaration creates a new scope, where you can access the members of parent scope but any modification gets applied to current scope (true for string, int, boolean types), so

$scope.age = true;  //Creates a new property on the current scope.

You should use the . notation or object if you need to handle this scenario. So age should be a object like

$scope.age={overage:true};

and the corresponding binding gets affected like

<div class="age red" ng-if="!(age.overage)">

whereever age is used.

Please go through this https://github.com/angular/angular.js/wiki/Understanding-Scopes

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.