Search code examples
javascripthtmlangularjsangular-directiveangular-controller

Return value of an Angular Directive and based on value have ng-if to display content


I have a Directive that returns a 0 or 1

 <my-code inputcode="{{ data.valBit }}"></my-code>

So data.valBit will be a 0 or 1

If it is a 1 , then I want it to display an HTML section of code, how can I do that? Problem with returning all the html from the directive is that it is put of a form along with ngmessage validation , so it is not fun to pass form or mess with link or compiler

<div ng-if="data.valBit == 1">
    part of my form,  with ngmessage etc...   $error  etc... 
    .......
</div>

Is this possible to get a callback from a directive that I can evaluate and decide whether to show or hide a section of html?


Solution

  • Most simple way to do it is taking advantage of two way data binding.
    In Your case, the problem is that your are passing to the directive the evaluated value instead of the variable.
    Just remove the braces in your directive argument <my-code inputcode="data.valBit"></my-code>.

    Example: (PLUNKER)

    HTML

    <my-code inputcode="data.valBit"></my-code>
    <p ng-if="data.valBit == 1">
      part of my form,  with ngmessage etc... $erroretc... 
    </p>
    

    DIRECTIVE

    app.directive('myCode', function() {
      return {
        restrict: 'E',
        scope: {
          inputcode: "=" //two way binding
        },
        link: function(scope, element, attrs){
          scope.inputcode = 1;
        }
      }
    })