0

我有一个带有两个控制器、posts 和 ctrl 的 Angular 应用程序。我还使用 ng-if 来隐藏/显示几个元素。

Ctrl 控制器将值 $scope.age 设置为 true,如果我在 Posts 控制器中设置 age=true,则 ng-if-things 被触发,现在它们不会被触发,直到我重新加载页面。为什么不,我应该怎么做?

<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);
    };
}
4

1 回答 1

1

ngController指令创建一个新范围,该范围继承自父范围。您的内部ngController声明创建了一个新范围,您可以在其中访问父范围的成员,但任何修改都将应用于当前范围(对于字符串、整数、布尔类型为 true),所以

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

.如果您需要处理这种情况,您应该使用符号或对象。所以年龄应该是一个对象

$scope.age={overage:true};

并且相应的绑定会受到影响

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

无论在哪里age使用。

请浏览此https://github.com/angular/angular.js/wiki/Understanding-Scopes

于 2013-09-02T14:49:42.140 回答