如何使用角度指令控制器动态单击复选框

时间:2016-03-22 21:10:30

标签: javascript angularjs checkbox

这是我的HTML

  <li 
    ng-repeat="myElement in myList">

    <input 
      type="checkbox" value="myElement"
      ng-model="checkState"
      ng-click="myDirective.updateSelectedElement(myElement, checkState)"/>
    <div>
      {{myElement.name}}
    </div>
  </li>

我有一个$broadcast事件

        $scope.$on('myEvent', function(event, data){
            // Change the checkbox state for the checkbox that have the same name in data
        }) 

问题是,由于我的复选框都是孤立的范围,我无法访问它,是否有办法访问具有特定myElement.name的复选框

由于

2 个答案:

答案 0 :(得分:0)

通过rootscope来完成它将解决您的问题

app.controller("ControllerA", ["$scope", "$rootScope", function($scope, $rootScope){
    $rootScope.$broadcast("myEvent");
}]);


app.controller("ControllerB", ["$scope", "$rootScope", function($scope, $rootScope){

    $rootScope.$on('myEvent', function(event, data){
        $scope.checkState = true;
    })
}]);

答案 1 :(得分:0)

这是我编写的代码的一个工作示例,用于说明如何使用事件从指令外部以编程方式检查和取消选中复选框。我在这个例子中使用按钮,但你也可以从控制器内部调用方法。

Example in Plunker

此外,作为最佳实践,如果您从rootScope调度事件并在rootScope上侦听它,请使用$ emit而不是$ broadcast,以便事件在rootScope开始和结束,并且不在范围内广播链

Angular Code

angular.module('app', [

]).controller('MainController', ['$scope', '$rootScope', function ($scope, $rootScope) {
    $scope.list = [{label: 'Camaro'}, {label: 'Chevette'}, {label: 'Corvette'}];
    $scope.checkItem = function (label, status) {
      $rootScope.$emit('checkItemEvent', {label: label, check: status});
    }; 
  }])

  .directive('checkboxDirective', function ($rootScope) {
    return {
      restrict: 'AE',
      template: '<input type="checkbox" ng-model="item.checkState"/><span>{{item.label}}</span>',
      require: 'ngModel',
      scope: {
        item: '=ngModel'
      },
      link: function ($scope) {
        console.log('$scope.item', $scope.item);
        $rootScope.$on('checkItemEvent', function (event, data) {
          console.log('data', data);
          if (data.label === $scope.item.label) {
            $scope.item.checkState = data.check;
          }
        });
      }
    };
  });

HTML

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainController">
    <h1>Checkbox demo</h1>
    <ul>
      <li ng-repeat="item in list">
        <checkbox-directive ng-model="item"></checkbox-directive>
      </li>
    </ul>
    <div>
      <button ng-click="checkItem('Corvette', true)">Check Corvette</button>
      <button ng-click="checkItem('Corvette', false)">Uncheck Corvette</button>
    </div>
  </body>

</html>