2013-07-23 55 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'來表示答案的另一半 –