search

Home  >  Q&A  >  body text

javascript - How do angularJS instructions expose API to external controllers?

<button>expand</button>
<my-menu></my-menu>

I want to click the button to expand menu, but how to expose the API of menu to button?
Or is there any other better way?

伊谢尔伦伊谢尔伦2743 days ago1437

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-06-17 09:17:37

    There is no need to expose any API, you only need to use custom attributes on the instructions for two-way data binding.
    For example, if you need to show or hide, you can use a display attribute on the command, for example:

    <my-menu display="someCtrlValue" ></my-menu>
    
    

    Then control this value in your controller, such as

     if(condition){
       $scope.someCtrlValue = true;
     }
     

    Of course you only need to specify the two-way binding attributes in the command;

     Module.directive("myMenu", function(){
       return {
           scope: {
               display : '='
           }
           ...
       }
     })

    reply
    0
  • 高洛峰

    高洛峰2017-06-17 09:17:37

    You can specify a two-way binding attribute, such as collapse, when writing the my-menu command, and then use it through <my-menu collapse="val"></my-menu>, and then use the button's The ng-click event can control the val variable (true/false). Then when defining instructions, two-way binding is achieved through independent scopes. Please refer to this article at http://xgfe.github.io/2015/12...

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-17 09:17:37

    Provide a method to perform emit in the instruction, and then the controller performs on monitoring.
    In addition, generally the instruction needs to pass the value externally and internally to achieve the flexibility of the instruction. If so, does it not have to modify the instruction every time the API is modified?

    reply
    0
  • Cancelreply