Angular.js中的构造方法

时间:2018-12-21 00:50:43

标签: angularjs controller

最近在尝试使我的构造函数与我的angular项目一起工作时遇到了很多问题,因此我创建了一个测试组件。该代码应该通过单击按钮来切换显示“ hello test”的消息。请让我知道为什么我的构造函数没有响应。

<!DOCTYPE html>
  <head>
  <meta charset="UTF-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  <script type="text/javascript" src="app.component.js"></script>
</head>
<body>
    <div ng-app="postEvent" 
        ng-controller="postCtrl">
        <button> reg button test </button>
        <button ng-click="toggle()"> toggle test </button>
        <button ng-show="state"> state test </button>
    </div>
</body>

// app.component.js
var postEvent = angular.module("postEvent", []);
postEvent.controller("postCtrl", function($scope) {        
        $scope.toggle = function () {
        $scope.state = !$scope.state; 
    }
});

1 个答案:

答案 0 :(得分:1)

删除

function ctrl($scope) {    
}

这里没有必要。

演示

<head>
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="postEvent" ng-controller="postCtrl"> <button ng-click="toggle()">test </button> <div ng-show="state" > hello test </div> </div> 
<script type="text/javascript">
    var postEvent = angular.module("postEvent", []);
    postEvent.controller("postCtrl", function($scope) {        
            $scope.toggle = function () {
            $scope.state = !$scope.state; 
        }
    });
</script>