• Angular1.0 在Directive中调用Controller的方法


    Controller中定义了$scope.method = function(){}

    Directive中需要引入$scope

    http://stackoverflow.com/questions/23636727/how-to-call-controller-function-from-directive

    JS:
    
    angular.module('myApp', [])
    .controller('MyController', function($scope){
      $scope.showAlert = function(value){
        alert('Called from directive: ' + value);
      };
    })
    .directive('myDirective', function(){
      return {
        restrict: 'E',
        scope: {
          alert: '&'
        },
        controller: function($scope){
          $scope.value = 'directive scope value';
        },
        template: '<button ng-click="alert({message: value})">Alert</button>'
      }
    });
    HTML:
    
    <body ng-app="myApp" ng-controller="MyController">
      <my-directive alert="showAlert(message)"></my-directive>
    </body>

    My recommendation is to use $emit instead of calling a method of the controller directly in your directive.

    Directives should be always independent components, if inside the directive there is a call to a method from a controller(outside the directive) this will create a dependency between my directive and the controller and of course this will force one not being able to exist without the other.

    If I would have to apply a design principle to a directive it will be the S in SOLID, Single responsibility principle. Directives should be able to encapsulate and work independently.

    On my controller the event is captured using $on like:

    $scope.$on("ValueChanged", function(event, ars){
       ... //your event has been triggered.    
    });

    或者

    var directive= function ( $sessionStorage, $localStorage) {
                function work(scope, element, attrs, formCtrl) {
                    var watchPromise = attrs.createClaimForm || null;
                    element.bind('keypress', function (event) {
    //此处scope就是$scope 
                            scope.addBlankRowData();
                        }
                    });
    
     return {
                    require: "form",
                    restrict: "A",
                    link: work
                }
     };

    Controller中this.method = function(){}是获取不到的, 必须$scope

  • 相关阅读:
    执行游戏时出现0xc000007b错误的解决方法
    html中#include file的使用方法
    使用ServletFileUpload实现上传
    java环境变量配置
    微软之左旋转字符串
    Ubuntu下很给力的下载工具
    hibernate官方新手教程 (转载)
    mssql数据库游标批量改动符合条件的记录
    PageRank算法
    Myeclipse7.5 下载 安装 注冊 注冊码 100%成功
  • 原文地址:https://www.cnblogs.com/haimingpro/p/6677842.html
Copyright © 2020-2023  润新知