gpt4 book ai didi

javascript - 变量捕获按钮并将其传递给 Angular 服务

转载 作者:行者123 更新时间:2023-11-28 06:24:16 25 4
gpt4 key购买 nike

社区您好,我正在使用 Angular 开发一个项目,但我遇到了以下问题:

我想捕获按钮内部的值,该值来自 Controller ,然后单击将此值传递给服务,并且该服务应转到另一个 Controller :

HTML

<div ng-app="myApp">

<div ng-controller="capturaCtrl">
<!--capturar valor en 'algunaVariable' con ng-click o ng-model se me ocurre para pasarla al service captura -->
CODIGO A CAPTURAR: <button>{{capturame}}</button>
</div>

<br>

<div ng-controller="recibeCtrl">
CODIGO CAPTURADO:
{{codigo}}
</div>

JS

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

app.factory('captura', function(){
var codigo = algunaVariable; // <== variable que reciba del controllar capturaCtrl
return{
getCodes: function(){
return codigo;
}
}
});

app.controller('capturaCtrl', ['$scope', 'captura', function($scope, captura){
$scope.capturame = '1111';

}]);


app.controller('recibeCtrl', ['$scope', 'captura', function($scope, captura){
$scope.codigo = captura.getCodes();

}]);

在这里,我给你我的代码:https://jsfiddle.net/alx_lopz/wgfh3dLa/5/

最佳答案

向您的工厂添加 setter 函数。

  app.factory('captura',  function(){
var codigo = "initial value"; // <== variable que reciba del controllar capturaCtrl
return{
getCodes: function(){
return codigo;
},
setCodes: function(value) {
codigo = value;
return value;
}
}
});

ng-click 添加到您的按钮

CODIGO A CAPTURAR: <button ng-click="setCodigo(capturame)">
{{capturame}}
</button>

将检索转换为函数

CODIGO CAPTURADO: {{ codigo() }}

将函数放在范围内

  app.controller('capturaCtrl', ['$scope', 'captura', function($scope, captura){
$scope.capturame = '1111';
$scope.setCodigo = captura.setCodes;

}]);

app.controller('recibeCtrl', ['$scope', 'captura', function($scope, captura){
$scope.codigo = captura.getCodes;

}]);

DEMO on JSFiddle .

关于javascript - 变量捕获按钮并将其传递给 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35259254/

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