代码之家  ›  专栏  ›  技术社区  ›  Crystal

如何启动按钮单击,根据视图上的控制器执行不同的操作?

  •  0
  • Crystal  · 技术社区  · 7 年前

    问题

    情况

    下面我有两个指令/控制器,它们共享相同的模板视图。所有数据都正确呈现- ng-click="{{::vm.action}}" 但是,单击时不会执行任何操作。如果我将语法更改为 ng-click="{{::vm.action()}}"

    代码

    <confirm-modal></confirm-modal>
    
    <error-modal></error-modal>
    

    情态动词html:

    <article>
        <h1>{{::title}}</h1>
        <p>{{::body}}</p>
        <button ng-click="{{::action}}">{{::button}}</button>
    </article>
    

    angular
      .module('common.modal')
      .controller('ConfirmModalController', ConfirmModalController)
      .directive('confirmModal', confirmModal);
    
    /* @ngInject */
    function confirmModal() {
    
      var directive = {
        templateUrl: 'app/widgets/modals/modal.html',
        restrict: 'E',
        controller: ConfirmModalController,
        controllerAs: 'vm',
        bindToController: true
      };
    
      return directive;
    }
    
    function ConfirmModalController(modalService) {
    
      var vm = this;
    
      vm.title = 'Confirm Your Subscription';
    
      vm.body = '$8.99 per month will be billed to your account.';
    
      vm.button = 'Subscribe';
    
      vm.action = function () {
        console.log('confirm subscription');
        modalService.confirmSubscription();
      };
    
    }
    

    错误模式。指令。js(和控制器)

    angular
      .module('common.modal')
      .controller('ErrorModalController', ErrorModalController)
      .directive('errorModal', errorModal);
    
    /* @ngInject */
    function errorModal() {
      var directive = {
        templateUrl: 'app/widgets/modals/modal.html',
        restrict: 'E',
        controller: ErrorModalController,
        controllerAs: 'vm',
        bindToController: true
      };
    
      return directive;
    }
    
    function ErrorModalController(modalService) {
    
      var vm = this;
    
      vm.title = 'There was an error with your request';
    
      vm.body = 'Please contact administrator regarding this error';
    
      vm.button = 'Dismiss';
    
      vm.action = function () {
        console.log('error on subscription');
        modalService.closeAllModals();
      };
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   JC Ford    7 年前

    {{::vm.action}} 是对函数的引用 vm.action {{::vm.action()}} 在呈现模板时执行该函数。Angular将该函数的返回值(本例中未定义)绑定到 ng-click

    <article>
        <h1>{{::vm.title}}</h1>
        <p>{{::vm.body}}</p>
        <button ng-click="vm.action()">{{::vm.button}}</button>
    </article>