gpt4 book ai didi

javascript - 如何使用 angularjs 指令的内置服务?

转载 作者:行者123 更新时间:2023-12-03 02:27:33 24 4
gpt4 key购买 nike

我可以使用 angularjs 内置的 $location 服务从 URL 获取一些 ID。现在,我需要在页面加载时使用该 ID 调用服务,然后需要以某种方式呈现响应。

我正在使用 ng-init ,例如:

ng-init="uid=$location.path().substring($location.path().lastIndexOf('/') + 1); callToTheService(uid);"

当我执行时,这样 ng-init 就无法调用内置服务,这就是我未定义的原因。我在 AngularJS 中缺少什么?我必须以准确的方式配置它。

最佳答案

最好在 Controller 中对其进行初始化。只需将其绑定(bind)到范围即可。然后注入(inject)您的服务并从中调用函数。这是一个例子:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location, YourService) { // injections are important
$scope.uid = $location.path().substring($location.path().lastIndexOf('/') + 1);
$scope.log = function() {
YourService.callToTheService($scope.uid);
}
});

app.service("YourService", function() {
this.callToTheService = function(uid) {
console.log("UID: ",uid); // empty in this case
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="log()">Log UID</button>
</div>

关于javascript - 如何使用 angularjs 指令的内置服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48882147/

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