0

鉴于 JQuery UI 按钮的这个相当简单的角度包装器:

angular.module('Sample.controllers', [])
  .controller('mainController', ['$scope',
    function($scope) {
      $scope.jump =  function () {alert("jump");};
   }])
  .directive('jquiwButton', function() {
    return {
      scope: {},
      restrict: 'A',
      replace:true,
      link: function(scope, element, attrs) {
        var options = {};
        if (angular.isDefined(attrs["jquiDisabled"])) {
          options.disabled = attrs["jquiDisabled"];
        }

        if (angular.isDefined(attrs["jquiIconPrimary"])) {
          if (!angular.isDefined(options.icons.primary)) {
            options.icons ={};
          }
          options.icons.primary = attrs["jquiIconPrimary"];
        }

        if (angular.isDefined(attrs["jquiIconSecondary"])) {
          if (!angular.isDefined(options.icons.secondary)) {
            options.icons ={};
          }
          options.icons.secondary = attrs["jquiIconSecondary"];
        }

        if (angular.isDefined(attrs["jquiLabel"])) {
          options.label = attrs["jquiLabel"];
        }

        if (angular.isDefined(attrs["jquiText"])) {
          options.text = attrs["jquiText"];
        }

        element.button(options);
      }
    };
  });
  angular.module('Sample', ['Sample.controllers']);  

和标记。

<body ng-controller="mainController"> 
  <button jquiw-button jqui-label="Hello" ng-click="jump()">Hello</button>
</body>

它工作正常,直到我添加一个范围,此时我失去了使用标准角度绑定到外部范围的能力。在我的情况下,标记 `ng-click='jump()' 现在不起作用,因为它找不到在外部上下文中定义而不是在隔离范围内的方法 jump。现在我知道我可以专门将 ng-click 绑定回外部范围,但我想避免这样做,因为它需要了解我可能需要绑定的所有可能指令。

所以我的问题是:如何让其他指令在外部范围内工作,同时仍然具有隔离范围?

plunker: http ://plnkr.co/edit/eRoOeq?p=preview

删除第 8 行: scope: {},它 ng-click 调用了正确的函数。

4

2 回答 2

2

使用ng-click="$parent.jump()".

于 2013-09-30T02:37:20.153 回答
1

&您可以使用绑定从隔离范围内引用父范围内的函数。这是根据指令文档从指令内的隔离范围调用函数的正确方法。

我创建了一个有效的 CodePen 示例来展示它完美地工作。

以下是相关部分:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.jump = function() {
    alert('jump called');
  };
});

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      call: '&'
    },
    link: function postLink(scope, element, attrs) {
      scope.call();
    }
  };
});

并在模板中:

<section ng-app="app" ng-controller="MainCtrl">
  <my-directive call="jump()"></my-directive>
</section>

我希望这有帮助。

于 2013-09-30T02:48:47.830 回答