Search code examples
angularjsangular-directive

Pass parameter for custom directive


Using Angular 1.5 with components.

Some parent HTML that contains custom directive:

<my-thing resetFields='$ctrl.bReset'></my-thing>

EDIT: instead of resetFields, here I should have used reset-fields - this was why I got the undefined below.

Parent controller:

function parentController() {
            var ctrl = this;
            ctrl.bReset= true;
        }

Here is the component declaration for myThing:

alert(ctrl.reset); // alert is called in controller, but shows undefined
function myThingComponent() {
            this.controller = {};
            this.bindings = {};
            var component = this;
            component.templateUrl = 'myThing.html';
            component.controller = myThingCtrl;
            component.transclude = true;
            component.bindings = {
                resetFields: '<' // one way binding is needed
            };
        }

How can I send such parameter and use it in the custom directive's controller - myThingCtrl? If the reset value is true I will perform some action and on false another action. (Generally the question I guess is - how can I read a value from the parent inside the child component.)


Solution

  • For achive this propouse you have create a directive like below:

    angular.module("yourModule")
        .directive("myThing",function(){
            return {
                ...
                restrict : "E",
                scope:{
                        reset:"=reset",
                        ....
                },
                .....
                }
            }
        });
    

    in component way

    angular.module('yourModule').component('myThing', {
    ...
      bindings: {
        reset: '='
      }
    });
    

    The key point hear is use scope propertie like above and say that reset (reset in the left part) attribute in your directive is binded with a scope properties named reset (=reset rigth part) with the "=" you say that yoh have a two way data-binding.

    I hope that this can help you