Javascript js:为什么用一个简单的helper函数改变$scope会导致不相关的{{…}表达式?

Javascript js:为什么用一个简单的helper函数改变$scope会导致不相关的{{…}表达式?,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,好的,这里有一个git差异: ... function makeSomeCtrl() { + var identity = function (x) {return x;}; + $scope = identity($scope) return function($scope) { ... 突然间,所有的角都出现在“{{page.hello}}}”页面而不是“hello,World” 到底为什么 编辑:这里有一个Plunker演示了这种行为: 分辨率 所以,$scope不在范围内。

好的,这里有一个git差异:

...
function makeSomeCtrl() {
+    var identity = function (x) {return x;};
+    $scope = identity($scope)
return function($scope) {
...
突然间,所有的角都出现在“{{page.hello}}}”页面而不是“hello,World”

到底为什么

编辑:这里有一个Plunker演示了这种行为:

分辨率 所以,
$scope
不在范围内。哦!这既令人尴尬又令人尴尬

再次编辑:未解决 Plunker中的代码并不反映我试图调试的原始代码。也就是说,原始代码的问题不是范围错误。这是我在起草Plunker时犯的一个错误。下面是一个更新的Plunker,它更准确地反映了我正在处理的代码:


在呈现的页面中生成一个漂亮的fat“{value}}”。

您无法在
makeCtrl
中访问
$scope
,因为Angular不会将其注入到您的函数中。如果将行
$scope=identity($scope)
移动到
randominityctrl
中,代码工作正常。

这是一个简单的操作,
$scope
在尝试调用它之前没有定义

  function makeCtrl(someVar) {
    function identity(o){return o;}

    //Where did I come from?
    $scope = identity($scope)

    function RandomIdentityCtrl($scope){
      $scope.beforeIdentity = "Before Identity";
      $scope.afterIdentity = "After Identity";
    }
  return RandomIdentityCtrl;
  }
如果您只是将其向下移动到构造函数中,您将看到它工作得很好:

  function makeCtrl(someVar) {
    function identity(o){return o;}


    function RandomIdentityCtrl($scope){
      $scope.beforeIdentity = "Before Identity";

      //Now I work! Yay!
      $scope = identity($scope)

      $scope.afterIdentity = "After Identity";
    }
  return RandomIdentityCtrl;
  }
更新 查看此处的更新后:

看来你只是打了几个错字

在您的功能中有一个:

  function makeCtrl(x) {
    function Ctrl($scope){
      addSomeValue($scope, x)
    }

  //Should be 'Ctrl'
  return RandomIdentityCtrl;
  }
还有一个在HTML模板中:

<!-- Should be "Ctrl" -->
<div class="container" ng-controller="RandomIdentityCtrl">


再次修复这些问题会导致期望的行为:

确实需要更多的上下文,因为这样做很好:这既让人感到安慰,也让人感到痛苦。我将为您提供更多contexct。当您看到不相关的Angular表达式
{{..}}
时,通常意味着存在异常或Angular未运行(这里似乎不是这样)。检查您的控制台是否有错误errors@Josh我分叉了你的Plunker,使它更接近我的实际代码。当我运行你的Plunker时,我得到一个异常:Error:[ng:areq]参数'RandomIdentityCtrl'不是一个函数,获取了未定义的$scope,而不是使用someVar作为参数也修复了它。@JamesWaddington-除了
$scope
在该上下文中不可用,因为它在Angular获得它之前进行计算。结果是Angular随后将用于注入的构造函数,但不是示例plunker中使用的方式。谢谢。我需要去睡一会儿:P@Josh,您正确识别的范围错误是我在编辑plunker时犯的错误。原始代码没有那个错误。我已经适当地更新了我的问题。介意再看一眼吗?谢谢你指出我的plunker代码中的错误。不幸的是,这实际上并不反映我的原始代码。我已经适当地更新了我的问题,并添加了另一个plunker链接供您查看。介意看一看吗?@stewSquared您更改了
RandomIdentityCtrl
函数的名称,但没有在它引用的任何位置。谢谢。在实际的代码库中可能类似。我讨厌未键入的模板
<!-- Should be "Ctrl" -->
<div class="container" ng-controller="RandomIdentityCtrl">