【问题标题】:Data binding in Angular jsAngular js 中的数据绑定
【发布时间】:2016-02-24 00:38:15
【问题描述】:

当我使用角度版本时。 "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js" 我的代码工作正常。但是当我使用这个角度版本时,我的代码不起作用。 “https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js”。

完整的 HTML 代码。

    <!DOCTYPE html>
    <html ng-app="">
    <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <head>
    <title>Angular Js Tutorial</title>
    </head>
    <body>
         <div ng-controller="Maincontroller">
             {{message}}
         </div>
        <script>
             function Maincontroller($scope)
              {
                  $scope.message = "Hii how are you";
              }
        </script>
    </body>
   </html>

我没有所需的输出。它只是打印。

   {{message}}

【问题讨论】:

标签: javascript html angularjs


【解决方案1】:

从 Angular 1.3 开始,您不能在全局范围内声明控制器。

重写你的控制器MainController的声明

// Declaration of the module
angular.module('myApp', []);

// Declaration of the controller
angular.module('myApp').controller('MainController', function ($scope) {
    $scope.message = "Hii how are you";
});

关于以上改动,将&lt;html ng-app=""&gt;替换为&lt;html ng-app="myApp"&gt;

【讨论】:

  • 太棒了!我在下面发布了相同的内容
【解决方案2】:

您的代码几乎没有问题,

(i)你没有在任何地方声明模块。 (ii) 在 Angular 1.3 中,控制器不应在全局范围内声明。

这里是更正后的application

【讨论】:

    【解决方案3】:
    <!DOCTYPE html>
    <html ng-app="app">
      <head>
        <title>Angular Js Tutorial</title>
        <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
      </head>
      <body >
        <div ng-controller="MainController as mainCtrl">
          {{ mainCtrl.message }}
        </div>
        <script>
          (function() {
            'use strict';
            angular
              .module('app', []);
              .controller('MainController', ['$scope', function MainController($scope) {
                  $scope.message = "Hii how are you";
            }]);
          })();
        </script>
      </body>
    </html>
    

    请参考this

    【讨论】:

    • 如果您使用的是MainController as mainCtrl,请不要使用$scope。使用this
    【解决方案4】:
    <html>
    <head>
    <title>Angular JS Controller Example</title>
    <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/
    1.4.7/angular.min.js"></script>
    </head>
    
    <body>
    <h2>AngularJS Sample Controller Application</h2>
    
    <div ng-app = "ukApp" ng-controller = "ukController">
    <br>         
    {{name}}
    </div>
    
    <script>
    var mainApp = angular.module("ukApp", []);
    mainApp.controller('ukController', function($scope) { 
    $scope.name= "Umar Farooque Khan";
    });
    </script>
    
    </body>
    </html>
    

    使用上述代码完成上述任务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 2016-10-23
      相关资源
      最近更新 更多