angular $scope的值在$scope里的函数内部改变不了?



 html


 <input type="checkbox" checked ng-click="toggle()" ng-controller="Ctrl">
<div ng-show="a" ng-controller="Ctrl">demo</div>


 javascript


 app.controller('Ctrl', function ($scope) {
    $scope.a = true;
    $scope.toggle = function () {
        $scope.a = !$scope.a;
        console.log($scope.a);
        if (!$scope.$$phase) {
            $scope.$apply();
        }
    }
    window.s = $scope;
});

当我点击checkbox的时候,console.log得到的结果是对的,但是div却没有任何变化,而且我在console里输入


 javascript


 console.log(s.a);

得到的结果是不对的,a根本没变化
我再输入


 javascript


 s.a = false;
s.$apply();

这时div才有了变化
这是为什么?

angularjs JavaScript

清凉的小丝瓜 12 years ago

 var s = angular.element(domElement).scope(); // to get the current scope for the element
console.log(s.a);



 <div id='ctrl' ng-controller='Ctrl'>
    <input type="checkbox" checked ng-click="toggle()">
    <div ng-show="a">demo</div>
</div>

wxklr answered 12 years ago

Your Answer