简体   繁体   English

Javascript Iife angularjs示例

[英]Javascript iife angularjs example

I have a simple controller which works absolutely fine. 我有一个简单的控制器,可以正常工作。

var myApp = angular.module('myApp', []);
myApp.controller('ProductController', ['$scope', function ($scope) {
$scope.Message = "Hello World";
} ]);

However, if I want to put this inside a function, ie 但是,如果我想将其放在一个函数中,即

(function () { 
var myApp = angular.module('myApp', []);
myApp.controller('ProductController', ['$scope', function ($scope) {
$scope.Message = "Hello World";
} ]);
});

I get the following error Error: ng:areq Bad Argument Argument 'ProductController' is not a function, got undefined 我收到以下错误错误:ng:areq错误的参数参数'ProductController'不是函数,未定义

Html is like this HTML是这样的

 <body ng-app="myApp">
<div ng-controller="ProductController">
  {{Message}}
</div>
</body>

your iife is not correct, you are missing invoking part of iife(Immediately- invoked function expression), you are not invoking it 您的iife不正确,您缺少invoking iife的一部分(立即调用的函数表达式),没有在invoking

(function () { 
var myApp = angular.module('myApp', []);
myApp.controller('ProductController', ['$scope', function ($scope) {
$scope.Message = "Hello World";
} ]);
})();

Working Demo: 工作演示:

 (function () { var myApp = angular.module('myApp', []); myApp.controller('ProductController', ['$scope', function ($scope) { $scope.Message = "Hello World"; } ]); })(); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="myApp"> <div ng-controller="ProductController"> {{Message}} </div> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM