2014-05-17 19 views
0

我有下面的腳本如何同指令多次與父母使用AngularJS

// Code goes here 

angular.module('default', []) 
    .directive('webAbc', function($log) { 
    return { 
     restrict: 'A', 
     controller: function($scope, $element, $attrs, $transclude) { 
     this.checkboxes    = []; 
     this.updateLinkedCheckboxes = function(value) { 
      angular.forEach(this.checkboxes, function(checkbox, index) { 
      checkbox.setChecked(value); 
      }); 
     }; 
     } 
    }; 
    }) 
    .directive('webDef', function($log) { 
    return { 
     restrict: 'C', 
     require: '^webAbc', 
     link: function (scope, iElement, iAttrs, webAbc, transcludeFn) { 
     iElement.bind('change', function() { 
      webAbc.updateLinkedCheckboxes(iElement.prop('checked')); 
      scope.$apply(); 
     }); 
     } 
    }; 
    }) 
    .directive('webGhi', function($log) { 
    return { 
     restict: 'A', 
     require: '^webAbc', 
     link: function (scope, iElement, iAttrs, webAbc, transcludeFn) { 
     scope.setChecked = function(value) { 
      $log.log('This element ' + iAttrs.name + ' cheked: ' + (!value ? 'checked' : '')); 
      $log.log(value); 
      if (value) 
      { 
      iElement.attr('checked', 'checked'); 
      } 
      else 
      { 
      iElement.remoteAttr('checked'); 
      } 
     }; 

     webAbc.checkboxes.push(scope); 
     } 
    }; 
    }); 

應該選擇或不選擇在顯着列表中的所有複選框,但我不能使它與下面的工作解。

首先看起來,只有最後一個webGhi由於在控制檯中打印而可見。甚至更多,看來,我不能因某種原因取消選中複選框。

鏈接到一個例子:http://jsbin.com/difihabe/1/

謝謝。

回答

3

使用在webGhi指令的分離的範圍或它的所有四個實例將推同一範圍(父):

.directive('webGhi', function($log) { 
    return { 
    restict: 'A', 
    require: '^webAbc', 
    scope: {}, 
    link: ... 

此外代替添加/刪除所檢查的屬性任一使用的:

  1. jQuery的prop()功能:iElement.prop('checked', value);

  2. 直接設置DOM元素檢查屬性: iElement[0].checked = value;

演示:http://jsbin.com/tudotugi/2/

+0

這是偉大的。謝謝。爲了清楚起見,如果沒有定義局部作用域,那麼最後一個元素將覆蓋它,因此只有它被使用,是正確的?而設置本地範圍將使每個行都是唯一的,正確的? – Eugene

+1

指令的所有四個實例將使用相同的作用域(父級)。 'webAbc.checkboxes.push(scope);'將被調用四次,這意味着在數組中會有四個對父作用域的引用。所有四個實例將在同一範圍內定義'scope.setChecked = function(value)'。這意味着數組中的所有四個引用將具有由四個中最後一個定義的'setChecked',因爲它將覆蓋其他四個引用。由於'setChecked'函數包含了指令第四個實例的'iElement'的引用,所以在您的示例中,這是一個正在工作的(半工作)。 – tasseKATT