AngularJS控制器不起作用

时间:2015-02-14 19:01:31

标签: angularjs controllers

使用最新的ng库,我尝试了以下内容。

此档案:

<!DOCTYPE html>
<html>
<head>
    <title>Listing 4-2</title>
    <script src="js/angular.min.js"></script>
    <script>
        function MyFilterDemoCtrl($scope) {

            var someData = {
                firstName: 'JENNA',
                surname: 'GRANT',
                dateJoined: new Date(2010, 2, 23),
                consumption: 123.659855,
                plan: 'super-basic-plan'
            };

            $scope.data = someData;

        }
    </script>

</head>
<body ng-app ng-controller="MyFilterDemoCtrl">

<p>
    <!-- Unfiltered data -->
    <strong>First Name</strong>: {{data.firstName}}<br/>
    <strong>Surname:</strong> {{data.surname}}
</p>

<p>
    <!-- Filtered data -->
    <strong>First Name</strong>: {{data.firstName | lowercase}}<br/>
    <strong>Surname:</strong> {{data.surname | lowercase }}
</p>

</body>
</html>

显示此输出:

First Name: {{data.firstName}}
Surname: {{data.surname}}

First Name: {{data.firstName | lowercase}}
Surname: {{data.surname | lowercase }}

为什么?

BTW - MyFilterDemoCtrl控制器的唯一任务是使数据可供视图使用。正如您将在上一章中回忆的那样,将它置于范围内就可以做到这一点。

感谢。

学家

1 个答案:

答案 0 :(得分:1)

你必须告诉Angular控制器,如下所示:

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

myApp.controller('MyFilterDemoCtrl', ['$scope', function($scope) {
    var someData = {
        firstName: 'JENNA',
        surname: 'GRANT',
        dateJoined: new Date(2010, 2, 23),
        consumption: 123.659855,
        plan: 'super-basic-plan'
    };

    $scope.data = someData;
}]);