2017-02-21 109 views
0

角JS控制器功能不工作

function studentController($scope) { 
 
      $scope.student = { 
 
       firstName: "Mahesh", 
 
       lastName: "Parashar", 
 
       fullName: function() { 
 
        var studentObject; 
 
        studentObject = $scope.student; 
 
        return studentObject.firstName + " " + studentObject.lastName; 
 
       } 
 
      }; 
 
     }
<html> 
 
<head> 
 
    <title>Angular JS Controller</title> 
 
</head> 
 
<body> 
 
    <h2> 
 
     AngularJS Sample Application</h2> 
 
    <div ng-app="" ng-controller="studentController"> 
 
     Enter first name: 
 
     <input type="text" ng-model="student.firstName"><br> 
 
     <br> 
 
     Enter last name: 
 
     <input type="text" ng-model="student.lastName"><br> 
 
     <br> 
 
     You are entering: {{student.fullName()}} 
 
    </div> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"> 
 
    </script> 
 
</body> 
 
</html>
在加载到Internet Explorer这个我没有得到的全名。它仅显示为{{student.fullName()}}。

为什么我没有得到全名? 我做错了吗?

+0

必须声明的模块将在'NG-app'或使用'angular.bootstrap '在你的代码中的某处。否则,你的应用程序不被视为一个Angular应用程序。 – ValLeNain

回答

0

您错过了声明的部分: - 主角模块。你在ng-app属性中输入的那个(如果你不这样做,你没有一个Angular应用程序) - 你声明你的Angular控制器并将它附加到主模块。

通过

<div ng-app="myApp" ng-controller="studentController"> 

而在你的脚本替换

<div ng-app="" ng-controller="studentController"> 

,加

var app = angular.module('myApp', []); 
app.controller('studentController',['$scope', studentController]); 

只是你的函数之前。

此外,我没有看到你的脚本链接到HTML文档的位置(应该有另一个<script>标记,在加载Angular库之后,那个)。

0

更改对象属性fullName这样:

$scope.student = { 
        firstName: "Mahesh", 
        lastName: "Parashar", 
        fullName: function() { 
         return $scope.student.firstName + " " + $scope.student.lastName; 
        } 
       }; 
0

您需要初始化代码的应用程序模块,并且附上您控制器这个模块。

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

app.controller('controllerName', controllerFunc) 

此外,您还需要根模块名称添加到NG-应用程式,例如

ng-app="App"