AngularJS第二个程序不起作用

时间:2015-02-22 08:04:17

标签: asp.net-mvc angularjs

我正在通过一本书中学习AngularJS:“为.NET开发人员学习AngularJS

一项任务是编写一个程序来计算颜色变化的次数,当它大于一次时它将显示计数。

起初我曾尝试自己编写,然后,我尝试将我的代码与书中的代码进行比较,但我无法理解为什么我的程序无效。

任何人都可以建议我在哪里做错了!

下面是我用MVC视图编写的完整代码。

@{
    Layout = null;
}

<!DOCTYPE html>

<html ng-app>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Introduction</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-controller="ExampleController">
    <div>
        <label>My name:</label>
        <input type="text" ng-model="name" placeholder="Please enter name" /><br />
        <label>My Favorite color:</label>
        <select ng-model="color" ng-change="OnColorChanged()">
            <option value="">Please select</option>
            <option>Red</option>
            <option>Yellow</option>
            <option>Magenta</option>
        </select>
        <h3 ng-show="name">Hello! my name is {{name}}</h3>
        <h3 ng-show="color">
            My favorite color is
            <span title="{{color}}" style="background-color:{{color}}">&nbsp;&nbsp;</span>
        </h3>
        <div ng-show="colorChangeCount > 0">The favorite color was changed {{colorChangeCount}} times.</div>
        <script>
            function ExampleController($scope) {
                $scope.colorChangeCount = 0;
                $scope.OnColorChanged = function () {
                    $scope.colorChangeCount++;
                };
            }
        </script>
    </div>
</body>
</html>

以下是我在chrome中获得的输出,但它不是正确的输出。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可能需要注册应用和控制器:

@{
    Layout = null;
}

<!DOCTYPE html>

<html ng-app="myApp">
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Introduction</title>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-controller="ExampleController">
    <div>
        <label>My name:</label>
        <input type="text" ng-model="name" placeholder="Please enter name" /><br />
        <label>My Favorite color:</label>
        <select ng-model="color" ng-change="OnColorChanged()">
            <option value="">Please select</option>
            <option>Red</option>
            <option>Yellow</option>
            <option>Magenta</option>
        </select>
        <h3 ng-show="name">Hello! my name is {{name}}</h3>
        <h3 ng-show="color">
            My favorite color is
            <span title="{{color}}" style="background-color:{{color}}">&nbsp;&nbsp;</span>
        </h3>
        <div ng-show="colorChangeCount > 0">The favorite color was changed {{colorChangeCount}} times.</div>
    </div>
    <script>
        var app = angular.module('myApp', []);

        app.controller('ExampleController', ['$scope', function ($scope) {
            $scope.colorChangeCount = 0;
            $scope.OnColorChanged = function () {
                $scope.colorChangeCount++;
            };
        }]);
    </script>
</body>
</html>