【问题标题】:How to pass variable from the view to the $scope with $window service?如何使用 $window 服务将变量从视图传递到 $scope?
【发布时间】:2014-12-29 14:40:02
【问题描述】:

我想在 ng-init 中初始化数据,想在控制器中检索这些数据。

我有一个带有表单的视图。在这种形式中,我有以下输入:

<input class="form-control" type="text" id="name" name="name"
                    ng-model="type.name" required="true"
                    placeholder="Enter type name..." ng-init="reftypedefinition.name='{{type.name}}'"/>

在 Chrome 开发者工具中,我看到了 reftypedefiniton name 的值:

并在我的控制器中注入 $window 服务:

$scope.createType = function () { $scope.reftypedefinition.name = $window.reftypedefinition.name;

};

当我运行时出现错误:

TypeError: Cannot read property 'name' of undefined
    at Scope.RefTypeDetailsController.$scope.createType (http://localhost:8080/...js:74:63)
    at Parser.functionCall (http://localhost:8080/.../js/lib/angular.js:10846:21)
    at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:8080/.../js/lib/angular.js:19133:17)
    at Scope.$get.Scope.$eval (http://localhost:8080/ism-server/js/lib/angular.js:12701:28)
    at Scope.$get.Scope.$apply (http://localhost:8080/ism-server/js/lib/angular.js:12799:23)
    at HTMLButtonElement.<anonymous> (http://localhost:8080/.../js/lib/angular.js:19138:23)
    at HTMLButtonElement.x.event.dispatch (http://localhost:8080/.../js/lib/jquery.min.js:5:10006)
    at HTMLButtonElement.x.event.add.y.handle (http://localhost:8080/**/js/lib/jquery.min.js:5:6796) 

怎么了?为什么名称在控制器上不可用? 感谢您的任何建议

【问题讨论】:

    标签: angularjs scope


    【解决方案1】:

    您实际上并没有使用ng-init 将其存储在$window 中。您正在直接在范围内对其进行初始化。因此,将您的代码更改为:

    $scope.reftypedefinition = {};
    $scope.createType = function () {
        console.log('name', $scope.reftypedefinition);
    };
    

    【讨论】:

    • 你是对的。我更改了我的代码,但现在我不明白发生了什么。在视图中,我有 html 代码 ng-init="reftypedefinition.name='Test'" 但在控制台日志中我有: {name:"{{type.name}}"} 变量在视图中进行评估,但是不在控制器中。
    【解决方案2】:

    您需要先在控制器中创建 $scope.reftypedefinition 对象。

    【讨论】:

      【解决方案3】:

      试试这个:

      ng-init="reftypedefinition={name : type.name}"
      

      【讨论】:

      • 你是对的。我更改了我的代码,但现在我不明白发生了什么。在视图中,我有 html 代码 ng-init="reftypedefinition.name='Test'" 但在控制台日志中我有: {name:"{{type.name}}"} 变量在视图中被评估但是不在控制器中
      • Angular 不会评估任何控制台日志语句。这是不可能的。它只评估视图。
      猜你喜欢
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多