AngularJS : broadcast event from directive

后端 未结 3 1924
南旧
南旧 2020-12-07 18:35

I\'ve seen people doing this from wherever in their code:

$rootScope.$broadcast(\'someEvent\', someParameter); 

and then in some controller

3条回答
  •  盖世英雄少女心
    2020-12-07 19:16

    Here is a TypeScript example of how to call back a method on the controller from an embedded directive. The most important thing to note is that the directive's parameter name for your callback uses a & when defined, and when calling that callback you should not use positional parameters but instead use an object with properties having the names of the parameters in the target.

    Register the directive when you create your app module:

    module MyApp {
        var app: angular.IModule = angular.module("MyApp");
        MyApp.Directives.FileUploader.register(app);
    }
    

    The registration code is as follows:

    module MyApp.Directives.FileUploader {
      class FileUploaderDirective implements angular.IDirective {
          public restrict: string = "E";
          public templateUrl: string = "/app/Directives/FileUploader/FileUploaderDirective.html";
    
          //IMPORTANT - Use & to identify this as a method reference
          public scope: any = {
            onFileItemClicked: "&"
          };
          public controller: string = "MyApp.Directives.FileUploader.Controller";
          public controllerAs: string = "controller";
          public bindToController: boolean = true;
          public transclude: boolean = true;
          public replace: boolean = true;
      }
    
      export function register(app: angular.IModule) {
          app.controller("MyApp.Directives.FileUploader.Controller", Controller);
          app.directive("fileUploader", () => new FileUploaderDirective());
      }
    }
    

    The directive's controller would look like this

    module MyApp.Directives.FileUploader {
        export class Controller {
            public files: string[] = ["One", "Two", "Three"];
            //The callback specified in the view that created this directive instance
            public onFileItemClicked: (fileItem) => void;
    
            // This is the controller method called from its HTML's ng-click
            public fileItemClicked(fileItem) {
                //IMPORTANT: Don't use comma separated parameters,
                //instead use an object with property names to act as named parameters
                this.onFileItemClicked({
                    fileItem: fileItem
                });
            }
        }
    }
    

    The directive's HTML would look something like this

    • {{ item }}

    The main view will have an instance of your directive like so

    
      
    
    

    Now all you need on your MainController is a method

    public fileItemClicked(fileItem) {
      alert("Clicked " + fileItem);
    }
    

提交回复
热议问题