gpt4 book ai didi

javascript - 解释 $apply 和 $eval |我可以用其他功能代替它们吗? AngularJS

转载 作者:行者123 更新时间:2023-12-03 07:35:14 26 4
gpt4 key购买 nike

我有一个 stripe 指令,它将一个值 a from 指令传递给 Controller ​​。

指令

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;

}]);

Controller :

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。

我还想知道指令如何将值传递给 Controller ​​。请解释一下代码,它是如何工作的。

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已经在进行中。与摘要相同:$digest 已在进行中

来自 Fiddle 的 evalAsync 代码示例:

HTML:

<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)
});
}
});
}

希望这有帮助!

关于javascript - 解释 $apply 和 $eval |我可以用其他功能代替它们吗? AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35642127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com