【问题标题】:Isolating scope in AngularJS directiveAngularJS指令中的隔离范围
【发布时间】:2015-12-11 15:24:41
【问题描述】:

我对 Angular 很陌生,我正在尝试编写自己的指令来了解这些对象的工作原理。 我的问题在于如何隔离指令的范围,以便我可以在同一个控制器中多次使用它。

我在这里创建了一个 plunker 来更好地解释情况:http://plnkr.co/edit/NsISESR9sIs5Nf577DX4?p=preview

html:

<body ng-controller="MainCtrl">
  <button id="button1" ng-click="dummyClickFoo()" wait-button>Foo</button>
  <button id="button2" ng-click="dummyClickBar()" wait-button>Bar</button>
</body>

js:

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

app.controller('MainCtrl', function($scope) {
    $scope.dummyClickFoo = function() {
        $scope.startSpinner();

        setTimeout(function() {
                $scope.stopSpinner();
          }, 3000);
    };

    $scope.dummyClickBar = function() {
        $scope.startSpinner();

        setTimeout(function() {
                $scope.stopSpinner();
          }, 3000);
    };
});


app.directive('waitButton', function() {
    return {
        restrict: 'A',
        controller: ['$scope', '$element', function($scope, $element) {
            $scope.startSpinner = function() {
                alert($element.attr('id'));
            };

            $scope.stopSpinner = function() {
                alert($element.attr('id'));
            };
        }]
    };
});

基本上它只适用于一个按钮,但它不适用于两个按钮,我知道我应该隔离它们的范围,但我不知道如何......我见过周围的例子,但他们使用额外的属性来在我需要调用内部方法时传递变量。

有人可以帮我弄清楚怎么做吗? 谢谢!

【问题讨论】:

标签: javascript angularjs angularjs-directive isolate-scope


【解决方案1】:

您可以通过在指令定义中设置 scope: {} 来创建隔离范围。

您将无法从您的控制器调用startSpinner 和stopSpinner,您不应该这样做!在指令中使用 ng-click 或在指令中而不是在控制器中绑定点击处理程序。由于您的指令没有标记,我建议您使用后者:

// added after the directive controller definition
link: function(scope, element) {
   element.on("click", function() { scope.startSpinner() });
}

【讨论】:

  • 谢谢...这很简单,但是我怎样才能调用 stopSpinner() 方法呢?
  • 就像 oyu 以前一样。您还可以在单​​击处理程序中设置超时。 scope.startSpinner() 只是一个示例,因为我懒得输入所有代码。
  • mm...我觉得有点笨,但我无法让它发挥作用,或者我误解了您的建议...我在这里更新了 plunkr:(plnkr.co/edit/RIMya1aGXpK6K8cgL4TW?p=preview)
  • 我理解你的意思......但我需要 stopSpinner() 可以在外部调用,因为现在我将 setTimeout 放在哪里会有一个异步函数......所以我需要,当这个函数是完成后,调用 stopSpinner 来停止调用它的按钮的微调器。
  • 这听起来不是问题。只需给函数一个回调,在异步函数完成后停止微调器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 2019-10-21
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 2012-12-27
相关资源
最近更新 更多