KingKongFrog KingKongFrog - 1 year ago 90
AngularJS Question

How to data bind directive that wraps an element in angular

I have a directive that creates a wrapper for an element. The problem with this is the "is-selected" class does not toggle based on the myValue value. I feel like it has something to do with how I'm implenenting ng-class with angular element but I'm not sure how to fix this. Any ideas??

Basically I want the wrapping element to have a class based on the the child model value.

<input my-checkbox type="checkbox" ng-model="myValue" ng-true-value="1" ng-false-value="0">

module.directive('myCheckbox', function($compile) {
return {
restrict: 'A',
scope: {
ngModel: '='
link: function(scope, element) {
element.attr('type', 'checkbox');
var wrapperEl = angular.element('<label class="checkbox-label" ng-class="{\'is-selected\': ngModel}"></label>');
if(scope.ngModel) {
wrapperEl.on('click', function() {
// console.log("wrapperEl: %o", wrapperEl);
var w = angular.element(element[0].parentNode);
if(scope.ngModel) {
} else {
wrapperEl = element.parent();
var checkEl = angular.element('<i class="Icon Icon--check text-success Icon--lg" ng-show="ngModel"></i>');
element.attr('style', 'position: absolute; left: -9999px;');

Answer Source

I fixed this by adding the $watch method.

scope.$watch('ngModel', function() {
  if(scope.ngModel) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download