javascript - AngularJS:$scope.watch 不工作

标签 javascript angularjs

我有一个元素a,它存储选中的复选框的数量。它已在我的部分更新。我可以访问 Controller 中的元素,但是,我需要将其设置为全局,因为我的大多数 Controller 都会使用它。我使用了 $rootScope 变量,并尝试在每次使用 $scope.watch 更新时将其设置为 a 的值,但是,这不起作用。

部分:

<p>You have selected: {{ a =(categories | filter:{checked: true }).length }} JOSCOS</p>

    <ul class="a">
    <li ng-repeat="item in categories" >
      <input type="checkbox" class="chk" ng-model = "item.checked">{{item.info.ct}}
      </input>
      </li>
     </ul>
<a href = "#x1" ng-click = "al()">Start the test</a>

我的 Angular Controller :

myApp.controller('OneController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/data/JOSCO.json').success(function(data) {
    $scope.categories = data;
  });
 $scope.a = 0
    $rootScope.cat = $scope.a;
    $scope.$watch('$scope.a',function () {
      $rootScope.cat = $scope.a;
   });
   $scope.al = function(){
      alert($scope.a); //outputs properly
   };
}]);

第二个 Controller (我对此有不同的部分):

myApp.controller('DetailsController', ['$scope','$rootScope' ,function($scope, $rootScope) {

  $scope.catno = $rootScope.cat;
  alert($scope.catno);  //outputs as '0'
}]);

最佳答案

$scope.$watch 接受多种不同的方式来指定您将监视的变量。您可以指定一个函数:

$scope.$watch(function(){return $scope.myvar}, someWatchHandler)

或者直接发送变量:

$scope.$watch($scope.myvar, someWatchHandler)

或将变量作为字符串传递:

$scope.$watch('myvar', someWatchHandler)

您正在使用其中的最后一个。请注意,您不需要在其前面添加 $scope —— 如果您这样做,它将找不到该变量。只需从 $scope.a 中删除 $scope 就可以了。

关于javascript - AngularJS:$scope.watch 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35110619/

相关文章:

javascript - 使用javascript从链接列表中获取链接名称

javascript - 在 AngularJS 中,一次点击两次调用是可以接受的方法吗?

javascript - 如何组合两个 JSON 字符串以存储在数据库中

AngularJS - 无需 Controller 即可访问模型属性

javascript - 追加新段落

javascript - 如何在 jQuery 中使用 jquery 变量?

javascript - ng-class 在 AngularJS 中不起作用

download - 在 angularjs 和express.js 之间进行下载

angularjs - 如何从 Angular 外部访问/更新 $rootScope

javascript - 如何使用 AngularJS 在按钮单击事件上动态添加 HTML 内容