【问题标题】:Angular cannot set property of undefinedAngular 无法设置未定义的属性
【发布时间】:2015-12-07 19:49:50
【问题描述】:

我不太明白为什么以下方法不起作用:

main.html

<div class="MainCtrl">
  <h1>{{message.test}}</h1>
</div>

main.js

angular.module('myApp')
  .controller('MainCtrl', function(someService, $location, $scope) {

    $scope.message.test = "blablabla";

  }
});

当我运行代码时,会出现以下错误:

TypeError:无法设置未定义的属性“测试” 在新 (http://localhost:9000/scripts/controllers/main.js:13:25) 在调用 (http://localhost:9000/bower_components/angular/angular.js:4473:17) 在 Object.instantiate (http://localhost:9000/bower_components/angular/angular.js:4481:27) 在http://localhost:9000/bower_components/angular/angular.js:9108:28 在 $route.link (http://localhost:9000/bower_components/angular-route/angular-route.js:977:26) 在 invokeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8746:9) 在 nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:8246:11) 在compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7637:13) 在 publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:7512:30) 在 name.$get.boundTranscludeFn (http://localhost:9000/bower_components/angular/angular.js:7656:16)

显然我错过了一些非常明显的东西..

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您正在为 undefined 对象定义一个属性,您必须在设置属性之前初始化您的对象。

    $scope.message = {};
    $scope.message.test = 'bla';
    

    【讨论】:

      【解决方案2】:

      你的测试在消息中不存在,你需要在$scope.message = {};之前,$scope.message.test = "blablabla";

      【讨论】:

        【解决方案3】:

        你的代码中的message不是一个对象,你必须让它:

        $scope.message = { test: 'blablabla' };
        

        【讨论】:

          【解决方案4】:

          您应该初始化您的 $scope.message 对象,但要安全地进行(以防它在其他地方定义,也许在某些情况下):

          $scope.message = $scope.message || {}; 
          $scope.message.test = "blablabla";
          

          【讨论】:

            猜你喜欢
            • 2019-04-20
            • 2018-06-28
            • 1970-01-01
            • 2019-05-08
            • 2021-11-27
            • 1970-01-01
            • 2022-10-30
            • 2023-02-10
            相关资源
            最近更新 更多