解释$apply和$eval |我可以用其他功能替换它们吗 |AngularJS.

Explain $apply and $eval | Can I replace them with other function | AngularJS

本文关键字:替换 AngularJS 功能 apply eval 我可以 解释 其他      更新时间:2023-09-26

我有一个条纹指令,它将值 a 从指令传递给控制器。

命令

angular.module('stripe', []).directive('stripeForm', ['$window',
function($window) {
  var directive = { restrict: 'A' };
  directive.link = function(scope, element, attributes) {
    var form = angular.element(element);
    form.bind('submit', function() {
      var button = form.find('button');
      button.prop('disabled', true);
      $window.Stripe.createToken(form[0], function() {
        button.prop('disabled', false);
        var args = arguments;
        scope.$apply(function() {
          scope.$eval(attributes.stripeForm).apply(scope, args);
        });
      });
    });
  };
  return directive;
}]);

控制器:

angular.module('myApp', ['stripe'])
.controller('IndexController', function($scope, $http) {
  $scope.saveCustomer = function(status, response) {
    $http.post('/save_customer', { token: response.id });
  };
});

.HTML

<form stripe:form="saveCustomer">
  <fieldset>
    <input type="text" size="20" data-stripe="number"/>
    <input type="text" size="4" data-stripe="cvc"/>
    <input type="text" size="2" data-stripe="exp-month"/>
    <input type="text" size="4" data-stripe="exp-year"/>
  </fieldset>
  <button type="submit">Save</button>
</form>

我的一所大学说使用$eval不是最佳实践,所以我需要一个替代方案来取代scope.$eval.

我还想知道指令如何将值传递给控制器。请解释代码,它是如何工作的。

scope.$apply(function() {
   scope.$eval(attributes.stripeForm).apply(scope, args);
});

编号 : https://github.com/gtramontina/stripe-angular

是的,$scope.$apply、$scope.$eval、$scope.$digest 的最佳替代品是 $scope.$evalAsync.。事实上,这是最佳实践。那么什么是,$evalAsync有什么用:

$evalAsync

它基本上$apply(更保证代码首先执行),但它确实会给你一个真正常见的错误:$apply is already in progress。摘要也是如此:$digest is already in progress .

来自小提琴的 evalAsync 的代码示例:

目录

<div ng-app="">
    <div ng-controller="Ctrl">
        <button ng-click="count()">Inc counter</button>
    </div>
    <div ng-controller="EmptyCtrl">
    </div>
</div>

Javascript

function EmptyCtrl() {
}
function Ctrl($scope) {
    $scope.counter = 0;
    $scope.count = function() {
        $scope.counter ++;
        console.log("setting value to "+$scope.counter)
    };
    var lastValue;
    $scope.$watch(function() {
        var value= $scope.counter;
        if (value!==lastValue) {
            lastValue = value;
            $scope.$evalAsync(function () {
                console.log("value in $evalAsync: "+value)
            });
        }
    });
}

希望这有帮助!