Skip to content Skip to sidebar Skip to footer

Ng-show Not Binding As Expected

I'm trying to have a simple 'toggle' on my form. If I click one button, then I should activate a correspondingly-named section, otherwise it should be hidden from view. My issue ap

Solution 1:

Here is a solution in which you create a new directive with it's own isolated scope. In my opinion, this is a better solution, especially since it allows you to have as many sub-steps as you want.

What you need to do when you create your isolate scope in the directive is have a property for both the name and for the isActive function. Since the name is just a string that you have defined in your html, you can specify it as an @ attribute so that is set in your directives scope to the string you specify in your html. I created the function (passing it to the directive using the & syntax) to be called showWhen and if you notice, in order to pass in the parameter name that you specify in your function in the html, you need to pass an object within your directive that uses name as a key with the directives name as the value.

The html:

<divng-controller='SubstepCtrl'><buttonactivates='CreateNewMeter'>
        Create new Meter
    </button><buttonactivates='UseExistingMeter'>
        Use Existing Meter
    </button><buttonactivates='UseImaginaryMeter'>
        Use Imaginary Meter
    </button><buttonactivates='none'>
        "Clear" all
    </button><substepname="CreateNewMeter"show-when="isActive(name)"><h1>Create New Meter</h1></substep><substepname="UseExistingMeter"show-when="isActive(name)"><h1>Use Existing Meter</h1></substep><substepname="UseImaginaryMeter"show-when="isActive(name)"><h1>Use Imaginary Meter</h1></substep></div>

The directive code:

.directive('substep', function() {
    return {
      restrict: 'E',
      scope: {
        name: '@',
        showWhen: '&'
      },
      transclude: true,
      template: '<div ng-transclude class="sub-step" ng-show="showWhen({name:name})"></div>'
    };
});

Here is a sample plunker: http://plnkr.co/edit/TKJehABKIPPHRbrUrqr3?p=preview

Solution 2:

Try this, which avoids creating your own directive:

<divng-controller='SubstepCtrl'><buttonng-click='setMeter("new")'>
        Create new Meter
    </button><buttonactivates='setMeter("existing")'>
        Use Existing Meter
    </button><divclass='sub-step'substep='CreateNewMeter'ng-show='meter === "new"'><h1>Create New Meter</h1></div><divclass='sub-step'substep='UseExistingMeter'ng-show='meter === "existing"'><h1>Use Existing Meter</h1></div></div>

set a function on your controllers' scope:

.controller('SubstepCtrl', function($scope) {
    $scope.activeSubstepName = undefined;
    $scope.isActive = function(name) {
        return$scope.activeSubstepName == name;
    };
    $scope.meter = null;
    $scope.setMeter = function(meterType) {
        $scope.meter = meterType;
    };
});

Post a Comment for "Ng-show Not Binding As Expected"