Home > Mobile >  how to use same component in multiple place with some logic in angularjs
how to use same component in multiple place with some logic in angularjs

Time:05-05

Well I have a directive/component/controller i.e <app-form></app-form> I am using this html page into multiple place but I want to to remove some specific field from different in place component how can I do in angularjs

in reacts we can do like this <app-form disableField></app-form> and if disabledField then disable particular field other wise nothing to do

again for better understanding for example we have one form having name, email and dob same form is using multiple place but at one place we are not interesting to display dob how can we disable or remove from specific place ?

please guide

CodePudding user response:

You have to use bindings in your component declaration. something on the lines of:

angular.module('app').component('appForm', {
    controller: 'AppFormCtrl',
    templateUrl: 'app-form.html',
    bindings: {
        disableField: "<", // use '<' to generate input on the component
    }
});

then in your app-form.html you can access the input var using the $ctrl object:

   <form>
     <input ng-if="$ctrl.disableField == true" type="text"/>
   </form>

And the you can pass whatever value you want in the scope of your root view:

<div>
   <!-- displays the form input according to the passed property's value -->
   <app-form disable-field="isFieldEnabled"></app-form>
   <!-- displays the form input -->
   <app-form disable-field="true"></app-form>
   <!-- does NOT display the form input -->
   <app-form disable-field="false"></app-form>
   <!-- does NOT display the form input, as disableField is evaluated an NULL in the component instance -->
   <app-form></app-form> 
</div>

isFieldEnabled is the property in your root controller $scope that will control the enabling / disabling of the input field in your component, but you can simply pass true or false if no logic is used.

You can attach whatever property you want, it doesn't have to be a boolean (but in this case I think it makes sense).

Also, notice that when defining the binded property 'disableField' in the Javascript environment, we use camelCase. The same property will be defined in the view / html environment using kebab-case.

You can also check the following answer to see how to generate output from the component instances: Angular.js, how to pass value from one component to any other

  • Related