简体   繁体   English

数据绑定不适用于angular中的模型属性

[英]Data binding not working for model property in angular

I am trying to put an Angular application together as I am learning. 我正在学习的同时,试图将Angular应用程序放在一起。 I am having trouble using data binding with a model property. 我无法在模型属性中使用数据绑定。

I have a model: announcer.model.ts 我有一个模型:announcer.model.ts

export class Announcer{
    constructor(public name: string){}
  }

I import the model in the register.component.ts: 我将模型导入register.component.ts中:

import { Announcer} from '../models/announcer.model'

  ....some code omited

announcer: Announcer
loading: Boolean

 constructor(private http: Http) { }

ngOnInit() {
       this.getRegister(); //I use this code to set the announcer variable
}


getRegister() : void
{
     this.loading= true;
     this.http.request('http://www.example.com/apiannouncer/show/0').subscribe((res: Response) => {
     var result = res.json();



     this.announcer= new Announcer(result.name);
    this.loading= false;
 } )

} }

In the template of the register.component.ts I can't use this: 在register.component.ts的模板中,我不能使用它:

 <div> {{ announcer.name }} </div>

I get this message: 我收到此消息:

Uncaught (in promise): Error: Error class - inline template:2:5 caused by: self.context.announcer is undefined

You need to use controllerAs syntax in your views, take a look at here and here . 您需要在视图中使用controllerAs语法,在此处此处查看

change your template to this: 将模板更改为此:

<div ng-controller="MyController as vm"
     <div> {{ announcer.name }} </div>
 </div>

what it does is simply put an instance of your class in $scope and make that class available in $scope via vm . 它的作用只是将您的类的实例放在$scope并通过vm使该类在$scope可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM