Why are my component bindings undefined in its controller?

前端 未结 9 1800
醉梦人生
醉梦人生 2021-01-31 13:22

I\'m writing a simple angular component. I\'m passing a parameter as a binding and display its value on the screen. All works fine: I can see the parameter being displayed on th

9条回答
  •  面向向阳花
    2021-01-31 13:51

    i will suggest some changes which you would really need to avoid these unusual bugs.

    app.component("test", {
      bindings: {
        "myContactId": "<"
      },
      controller:function(){
       var self=this;
       this.$onInit=function(){
        // do all your initializations here.
        // create a local scope object for this component only. always update that scope with bindings. and use that in views also.
    
           self.myScopeObject=self.myContactId
       }
      },
       template:'

    {{$ctrl.myScopeObject}}

    ' }

    some points :

    1. passing bindings to a component in html is always going to be kebab cased ex my-contact-id and its respective javascript variable will be cammal cased : myContactId.

    2. if you are passing the value insted of the object use '@' in bindings. if you are using an object and passing the object to bindigs use '<. if you want 2-way-binding to that object use '=' in the bindings config

     bindings:{
          value:'@',
          object:'<', // also known as one-way
          twoWay:'='
        }
    

提交回复
热议问题