加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS – ngClick,自定义指令和隔离范围问题

发布时间:2020-12-17 09:15:59 所属栏目:安全 来源:网络整理
导读:请考虑以下指令: (Live Demo) app.directive('spinner',function() { return { restrict: 'A',scope: { spinner: '=',doIt: "doIt" },link: function(scope,element,attrs) { var spinnerButton = angular.element("button class='btn disabled'i class='ic
请考虑以下指令: (Live Demo)
app.directive('spinner',function() {
  return {
    restrict: 'A',scope: {
      spinner: '=',doIt: "&doIt"
    },link: function(scope,element,attrs) {
      var spinnerButton = angular.element("<button class='btn disabled'><i class='icon-refresh icon-spin'></i> Doing...</button>");
      element.after(spinnerButton);

      scope.$watch('spinner',function(showSpinner) {
        spinnerButton.toggle(showSpinner);
        element.toggle(!showSpinner);
      });
    }
  };
});

这是这样使用的:

<button ng-click="doIt()" spinner="spinIt">Spin It</button>

当spinner的值(即本例中$scope.spinIt的值)为true时,应隐藏元素并改为显示spinnerButton.当spinner的值为false时,该元素应该是可见的,并且应该隐藏spinnerButton.

这里的问题是doIt()不在隔离范围内,因此不会在单击时调用.

实施该指令的“Angular方式”是什么?

我的建议是看看这些纺纱厂发生了什么. Be a little more API focused.

相关部分如下.我们使用常规回调来指示我们何时完成,因此微调器知道重置按钮的状态.

function SpinDemoCtrl($scope,$timeout,$q) {
  $scope.spinIt = false;

  $scope.longCycle = function(complete) {
    $timeout(function() {
      complete();
    },3000);
  };

  $scope.shortCycle = function(complete) {
    $timeout(function() {
      complete();
    },1000);
  };
}

app.directive('spinnerClick',scope: {
      spinnerClick: "=",},attrs) {
      var spinnerButton = angular.element("<button class='btn disabled'><i class='icon-refresh icon-spin'></i> Doing...</button>").hide();
      element.after(spinnerButton);

      element.click(function() {
        spinnerButton.show();
        element.hide();

        scope.spinnerClick(function() {
          spinnerButton.hide();
          element.show();
        });
      });
    }
  };
});

使用Angular风格的异步操作可以更好地工作,并通过在履行承诺时重置微调器来消除回调函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读