因此,我对AngularJS完全陌生,并按照课程学习并开始“学习”此框架。我观看了此页面顶部的两个截屏视频:

https://github.com/curran/screencasts/tree/gh-pages/introToAngular

观看了两个截屏视频并查看了一些示例后,我尝试创建自己的简单Angular应用程序,并尝试在其中使用某些控制器。现在,我有以下代码:

Index.html

<html ng-app="WIMT">
<head>
    <title>trying out angularJS</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript" src="../bower_components/angular/angular.min.js"></script>
    <script type="text/javascript" src="../JS/app.js"></script>

</head>
<body>

<div ng-controller="controllerA as a">
    {{a.varA}}
</div>

<div ng-controller="controllerB as b">
    {{b.varB}}
</div>

<div ng-controller="controllerC as c">
    {{c.varC}}
</div>

</body>
</html>


JS

(function() {

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


app.controller('controllerA',function($scope,$http){
    $scope.varA = "A";
});

app.controller('controllerB',['$scope',function($scope) {
    $scope.varB = "B";
}
]);

app.controller('controllerC',function($scope, $http) {
    var reg = this;

    reg.varC = "C";
});

})();


在尝试将varA绑定到控制器A中的作用域之后,我发现它不起作用,我在互联网上寻找解决方案。我发现了应该(可以?)工作的几种不同方式(B和C)。当我运行html时,只有选项C有效并显示C。 A和B均不显示任何内容。

为什么在此示例中选项A和B不起作用?

最佳答案

因为您使用的是controllerAs语法,所以这是第三个有效而第二个无效的原因。

<div ng-controller="controllerA as a">
    {{a.varA}}
</div>

<div ng-controller="controllerB as b">
    {{b.varB}}
</div>

<div ng-controller="controllerC as c">
    {{c.varC}}
</div>


如果要打印a.varAb.varB,则必须更改为以下内容:

<div ng-app="app">
    <div ng-controller="controllerA as a">
    {{varA}}
    </div>

    <div ng-controller="controllerB as b">
        {{varB}}
    </div>

    <div ng-controller="controllerC as c">
        {{c.varC}}
    </div>
</div>


http://jsfiddle.net/t0hhp5wz/

10-08 04:02