0

如何根据“bindto”属性检查或不检查以下复选框?我试过element.checked = true了,它没有选中复选框。有什么建议么?

directive('slideToggle', function () {
    return {
        replace: true,
        restrict: 'E',
        scope: {
            bindto: '='
        },
        template: '<input type="checkbox" name=""/>',
        link: function (scope, element, attrs) {
            console.log(scope); //shows scope.bindto as "true"
            console.log(scope.bindto); //undefined
        }
    }
}).

用法:

<slide-toggle bindTo="myItem.active"></slide-toggle>

4

2 回答 2

2

您应该在复选框上使用 ng-model 属性查看更新的代码

  <body ng-controller="test" >
          <input ng-model="myItem.active" />
       <slide-toggle bindto="myItem.active"></slide-toggle>
          <script>
              var app = angular.module('customControl', [])
              app.controller('test', function ($scope) {
                  $scope.userContent = 'hello';
                  $scope.myItem = { active: true };


              });

              app.directive('slideToggle', function () {
                  return {
                      replace: true,
                      restrict: 'E',
                      scope: {
                          bindto: '=bindto'
                      },
                      template: '<input type="checkbox" ng-model= "bindto"/>',
                      link: function (scope, element, attrs) {

                      }
                  }
              })
于 2013-07-23T20:31:46.733 回答
1

bindto 最初是未定义的,因为该指令是在父控制器更新范围之前链接的。您需要监听范围的变化:

link: function (scope, element, attrs) {
    scope.$watch("bindto", function (newValue) {
        console.log(scope.bindto); //undefined
    });
}

它在您的控制台中的“范围”上显示为“真”,因为您单击“范围”对象所花费的时间足以对其进行更新。

于 2013-07-23T20:28:39.870 回答