gpt4 book ai didi

javascript - Angular 服务给出 "TypeError: Cannot read property ' helloConsole' 未定义”

转载 作者:行者123 更新时间:2023-11-28 12:21:37 25 4
gpt4 key购买 nike

我正在研究 AngularJS 服务,但遇到了问题。

这是我的 Angular 代码:

var app = angular.module("todoListApp");

app.controller('MainController', MainController);

MainController.$inject = ['$scope'];

function MainController($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
};

app.service('dataService', function(){
this.helloConsole = function(){
console.log("console services");
};
});
That's my HTML Code

<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
<div class="actions">
<a href="" ng-click=" editing = !editing">Edit</a>
<a href="" ng-click="helloConsole()">Save</a>
<a href="" class="delete">Delete</a>
</div>
</div>
</div>

我试图做到这一点,以便当我单击“保存”时,控制台会向我显示“控制台服务”,但它给了我一个错误:

angular.js:13424 TypeError: Cannot read property 'helloConsole' of undefined

最佳答案

正确的 Angular 结构

您需要更改编写代码的方式。它应该看起来更像这样

angular.module("todoListApp", [])

.controller('MainController', ['$scope', 'dataService', function($scope, dataService){

$scope.helloConsole = dataService.helloConsole;

}])

.service('dataService', [function(){
this.helloConsole = function(){
console.log("console services");
};
}]);

这也是一个“数据服务”,这是通过 http 调用获取数据吗?因为如果是这样那就建一个工厂。

  • 业务逻辑 Controller
  • 数据请求工厂
  • 登录等服务
  • DOM 操作指令
  • 格式过滤器

关于javascript - Angular 服务给出 "TypeError: Cannot read property ' helloConsole' 未定义”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36677713/

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