2013-09-29 51 views
1

我想以動態方式在以下自定義元素中添加ngshow ...如何做到這一點?如何在編譯/鏈接中添加ngshow指令?

<toggler on-enable="main.enable()" on-disable="main.disable()"> 
    <div style="width:100px;height:100px;background-color:#2fa"> 
    <on>On state</on> 
    <off>Off state</off> 
    </div> 
</toggler> 

cf.directive('toggler', function() { 
    return { 
     restrict: 'AE', 
     scope: { 
      state: true, 
      onEnable: '&', 
      onDisable: '&' 
     }, 
     compile: function (elem, attrs) { 
      var onElem = elem.find('on'); 
      var offElem = elem.find('off'); 
      // WANT TO DO THIS 
      // onElem.ngShow = 'state'; 
      // offElem.ngShow = '!state'; 
     } 
    }; 
}); 
+0

你試過'elem.attr('ng-show','state')'?不確定它是否包含在jqLit​​e中。 – rogerz

回答

3

你這樣做是錯誤的。不要忘記AngularJS中的經驗法則:在不強制時避免DOM操作。

我想<on><off>也是自定義指令,因爲你不能簡單地添加標籤沒有任何定義的行爲。那麼,爲什麼不把ngShow屬性直接放在這個指令中呢?然後,指令的控制器(見documentation)將處理<on>/<off><toggler>之間的通信:

myApp.directive('toggler', function() { 
    return { 
     restrict: 'AE', 
     scope: { 
      state: '=', 
     }, 
     controller : [ 
      '$scope', 
      function ($scope) { 
       this.isOn = function() { 
        return $scope.state; 
       }; 
      }, 
     ], 
    }; 
}); 

myApp.directive('on', function() { 
    return { 
     restrict: 'AE', 
     require: '^toggler', 
     template: '<div ng-show="isOn()" ng-transclude />', 
     replace: true, 
     scope: true, 
     transclude: true, 
     link : function ($scope, element, attributes, togglerController) { 
      $scope.isOn = togglerController.isOn; 
     }, 
    }; 
}); 

myApp.directive('off', function() { 
    return { 
     restrict: 'AE', 
     require: '^toggler', 
     template: '<div ng-hide="isOn()" ng-transclude />', 
     replace: true, 
     scope: true, 
     transclude: true, 
     link : function ($scope, element, attributes, togglerController) { 
      $scope.isOn = togglerController.isOn; 
     }, 
    }; 
}); 

Fiddle

這樣一來,你就可以簡單地進行單元測試toggler,並在需要時延長他的行爲。

相關問題