首页 > 解决方案 > 将控制器中的对象行为定义绑定到 angularjs 中的指令范围函数

问题描述

难以将控制器中定义的对象行为绑定到隔离指令范围的功能。

plunker 链接https://plnkr.co/edit/YKrd3gaM4rJeP6jW

    (function(angular) {
  'use strict';
angular.module('docsIsoFnBindExample', [])
  .controller('Controller', ['$scope', '$timeout', function($scope, $timeout) {

    function Person(){
      this.name = "Some name",
      this.performAction = function(){
        console.log("doo some action");
        this.name = "changed name";
      }
    }
    function init(){
      $scope.person = new Person();

    }
    init();
  }])
  .directive('myDialog', function() {
    return {
      restrict: 'EA',
      scope: {
        'addPerformedAction': '&addPerformedAction'
      },
      template: '<button ng-click="next()">perform action</button>',
      link: function(scope, ele, atts){
        scope.next = function(){
          console.log("called next");
          scope.addPerformedAction();
        }
      }
    };
  });
})(window.angular);
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Function binding</title>
  

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
 

</head>
<body ng-app="docsIsoFnBindExample">
  <div ng-controller="Controller">
  {{message}}
  <my-dialog ng-hide="dialogIsHidden" add-performed-action="person.performAction">
  </my-dialog>
  <br/>
  <div>{{person.name}}</div>
</div>
</body>
</html>

标签: angularjsangularjs-directive

解决方案


对不起,我的错误必须在传递给指令时调用函数,发布这个而不是删除,以防万一有人遇到同样的问题。

老的 :

<my-dialog ng-hide="dialogIsHidden" add-performed-action="person.performAction">

新的:

<my-dialog ng-hide="dialogIsHidden" add-performed-action="person.performAction()">

推荐阅读