【问题标题】:AngularJS expression not working with adding controllerAngularJS 表达式不适用于添加控制器
【发布时间】:2020-05-19 04:28:56
【问题描述】:

当我将 ng-controller 添加到我的 index.html 时,表达式显示为 {{name || “你好”}} 和 {{ 年龄 || “我的朋友” }}。在我删除 ng-controller 后,表达式也无法工作。

它是controller.js

var PersonCtrl = function($scope){
    $scope.name = 'sky';
    $scope.age = 18;

    $scope.$watch('name', function(){
        console.log($scope.name);
    });

    $scope.$watch('age', function(){
        if($scope.age < 18){
            console.error('not correct');
        }
    });
};

它是 index.html

<!DOCTYPE html>
<!-- whole page is applied in AngularJS -->
<html ng-app>
<head>
  <meta charset="utf-8">
  <title>Learning of AngularJS</title>
  <!-- link with AngularJS -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <!-- <link rel="stylesheet" href="css/home.css"> -->
  <link rel="stylesheet" href="css/index.css">
</head>

<body>
<div id ="test" ng-controller="PersonCtrl">

 <h1>Name:</h1>
 <input size="35" style="height:50px" type="text" ng-model="name"
        placeholder="Enter your message, please.">

<h1> Age: </h1>
  <input size="35" style="height:50px" type="text" ng-model="age"
         placeholder="Enter your name, please.">
        <hr>
  <h1>{{name || "Hello"}}</h1>
  <h1>{{ age || "my friend" }}!</h1>

</div>
</body>
</html>

【问题讨论】:

    标签: javascript angularjs angularjs-controller


    【解决方案1】:

    把你的html标签改成

    <html ng-app="myApp">
    

    controller.js:

    // Define the Module. Only once in your code.
    var myApp = angular.module('myApp', []);
    
    // Define a controller for you module.
        myApp.controller('PersonCtrl', ['$scope', function ($scope) {
            $scope.name = 'sky';
            $scope.age = 18;
    
            $scope.$watch('name', function () {
                console.log($scope.name);
            });
    
            $scope.$watch('age', function () {
                if ($scope.age < 18) {
                    console.error('not correct');
                }
            });
        }]);
    

    【讨论】:

    • 感谢您的帮助。它确实有助于解决问题。希望你有一个美好的一天!
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2013-05-01
    相关资源
    最近更新 更多