Angular JS promise 不返回值

Angular JS promise not returning value

我是 Angular JS 的新手,我尝试将此 JS 加载到其中一个文件(cshtml 扩展名)中,它确实提示消息 'testing 1' 但没有提示 'testing 2'.我能知道这里有什么问题吗?你的友好指导将对我有很大的帮助。据我了解,当页面加载时,它 运行 $q.all 正确吗?但不知何故,它不起作用

var app = angular.module('myApp');
alert("Testing 1");
app.controller('ListController', function ($scope, $q, $http,$timeout) {
   
    function doTask1() {
        var deferred = $q.defer();
        deferred.resolve("Testing 2");
        return deferred.promise;
    }
    console.log("ListController instantiated");
    $q.all([
        doTask1(),
        
    ]).then(function (value) {
        
        alert(value);
    });
    
});

在 cshtml 文件中,(所有 angular 依赖文件都在 "~/Views/Shared/_Layout.cshtml" 中),控制台日志中没有错误,因此我知道 Angular 已成功导入

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-controller="ListController as listCtrl" class="margin-top-80px">

</div>

@section Scripts{

    <script src="~/Scripts/controllers/News/ListController.js"></script>
}

This is the output. It alerts the message "testing 1"

But the console log is empty

可能的原因是控制器没有被实例化。出于调试目的,包括一个控制台日志以指示控制器的实例化:

var app = angular.module('myApp');
alert("testing 1");
app.controller('ListController', function ($scope, $q, $http,$timeout) {
   
    function doTask1() {
        var deferred = $q.defer();
        deferred.resolve("testing 2");
        return deferred.promise;
    }

    //**********DEBUGGING
    console.log("ListController instantiated");

    $q.all([
        doTask1(),
        
    ]).then(function (value) {
        
        alert(value);
    });
    
});

解决了!感谢大家的帮助!

而不是

var app = angular.module('myApp');

我改成了

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

和 而不是

<div ng-controller="ListController as listCtrl" class="margin-top-80px">
</div>

尝试添加“ng-app”

<div ng-app="myApp ng-controller="ListController as listCtrl" class="margin-top-80px">
</div>