我想在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名称的值:
在我的控制器中,我注入$ 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)
有什么问题?为什么名称在控制器上不可用? 感谢您的任何建议
答案 0 :(得分:0)
您实际上并未使用$window
将其存储在ng-init
中。您正在范围内直接初始化它。所以将代码更改为:
$scope.reftypedefinition = {};
$scope.createType = function () {
console.log('name', $scope.reftypedefinition);
};
答案 1 :(得分:0)
您需要先在控制器中创建$ scope.reftypedefinition对象。
答案 2 :(得分:0)
试试这个:
ng-init="reftypedefinition={name : type.name}"