[英]how to call the same function from two different places in angularjs
I have two different HTML files.我有两个不同的 HTML 文件。 Select Button is there in two html files.
Select 按钮位于两个 html 文件中。 If I click that button I need to select the card.
如果我单击该按钮,我需要 select 卡。
I have two functions.我有两个功能。 First one is by default i need to show in screen.
第一个默认情况下我需要在屏幕上显示。
Second one is I need to show the same data in a popup modal.第二个是我需要在弹出模式中显示相同的数据。
<button type="button" class="btn btn-primary col-xs-12 col-md-12 col-lg-12"
ng-click="selectCard()">ADD CARD</button>
<button type="button" class="btn btn-primary col-xs-12 col-md-12 col-lg-12"
ng-click="selectCard()">ADD CARD</button>
These both are same html code.这些都是相同的 html 代码。
$scope.selectCard = function () {
$scope.select = true;
}
But my problem is,但我的问题是,
page.页。 html file is in popup modal.
html 文件处于弹出模式。
$scope.view = function () {
$uibModal.open({
templateUrl: 'page.html',
size: 'lg',
windowClass: 'page',
controller: function ($scope, $uibModalInstance, $timeout) {
$scope.selectCard = function(){
$scope.select = true;
}
}
});
}
Here inside popup modal also I need to write the same function again.在弹出模式中,我还需要再次编写相同的 function 。 Then only it is working.
然后只有它在工作。
Is any way is there to use the same function in both places.有什么方法可以在两个地方使用相同的 function。
For common functions, services are the best places.对于常用功能,服务是最好的地方。 You should add your service as Dependency Injection as required in your controllers.
您应该根据控制器中的要求将您的服务添加为依赖注入。
To create and inject service you can refer to this official angularjs documentation site: https://docs.angularjs.org/guide/services要创建和注入服务,您可以参考这个官方 angularjs 文档站点: https://docs.angularjs.org/guide/services
You can move the function to separate service and inject it in all places you need.您可以将 function 移动到单独的服务中,并将其注入您需要的所有地方。
In case it should be bound to mainController.js
, service function can use rxJs Subject
or just emit event to update value in mainController.js
.如果它应该绑定到
mainController.js
,服务 function 可以使用rxJs Subject
或只是发出事件来更新mainController.js
中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.