javascript - Angular 意外行为。自执行函数调用作用域函数

标签 javascript angularjs angularjs-scope

Working code sample.

简单的标记:

<!DOCTYPE html>
<html ng-app="APP">
<head></head>
<body ng-controller="myController">

    <script src="angular.min.js"></script>
    <script src="controller.js"></script>
</body>
</html>

简单的代码示例:

angular.module('APP', []).controller('myController', function($scope) {

    $scope.test = function() {
        console.log('Weird behaviour!')
    }

    (function() {} ()); //if you comment self-executing function console will be empty

});

而且范围行为真的很奇怪。您能解释一下为什么会这样吗?

最佳答案

您无意中制作了 test 作用域方法 IIFE,当前代码本质上是

$scope.test = (function() {
    console.log('Weird behaviour!')
})(undefined)

虽然 $scope.test 本身将是 undefined

应该是

$scope.test = function() {
    console.log('Weird behaviour!')
};

(function() {} ());

分号很珍贵。

关于javascript - Angular 意外行为。自执行函数调用作用域函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33658561/

相关文章:

javascript - polymer + Firebase (Polymerfire) : Cannot read property 'push' of undefined': 'this.$.query.ref.push(...)'

javascript - 如果用户想要访问需要登录认证的特定页面,如何重定向到 404 页面

angularjs - 在 Controller 之间共享异步数据而不发出多个请求

jquery - Angular JS 表单重新加载页面

javascript - 3 JS LineBasicMaterial如何在3D轴上绘制简单的粗线?

javascript - 下载表格到 Excel 并使用 ng-repeat 隐藏行

javascript - 第一次使用 redux。如何实现?

arrays - angularjs 比较两个数组

javascript - 监视嵌套在传递到 Angular 组件的多个对象中的更新

javascript - Angularjs:如何通过 Controller 将范围变量从一个 View 传递到另一个 View ?