2013-07-23 53 views
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>

+0

是应该有bindTo驼峰和指令bindto全部小写的模板? –

回答

1

bindto最初是未定义的,因为范围由父控制器更新前该指令被链接。你需要监听的范围发生了变化:

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

它在控制台中显示为“真”的“范围”,因为它把你点击进入“范围”对象的时间足够长,它要被更新。

+0

虽然这是正确的,但我还需要使用@Ajay – Webnet

2

您应该使用上的复选框NG-模型属性查看更新的代码

<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) { 

         } 
        } 
       }) 
+0

+1建议的'ng-model'来表示答案的另一半 –