简体   繁体   中英

Unable to set the value of bound property in angular component

I'm trying to implement a bound property for an angular component as explained in the component documentation and this example .

Unfortunately the values I'm assigning at the tag level or in the $onInit methods are never used. Nor is the value printed when I use it as a model value.

You can find the full code on plunker .

My binding definition:

(function(angular) {
  'use strict';

  function SearchResultController($scope, $element, $attrs) {
    var ctrl = this;
    ctrl.searchFor = 'nohting-ctor';

    ctrl.$onInit = function() {
      console.log('SearchResultController.$onInit: searchFor='+ctrl.searchFor);
      ctrl.searchFor = 'nothing-int';
    };

  }

  angular.module('myApp').component('searchResult', {
    templateUrl: 'searchResult.html',
    controller: SearchResultController,
    bindings: {
      searchFor: '<'
    }
  });
})(window.angular);

Template:

<p>SearchResult for <span ng-model="$ctrl.searchFor"</span></span></p>

How it's used:

<h1>Main Window</h1>
<search-input on-start-search="$ctrl.startSearch(value)"></search-input>
<search-result search-for="nothing-ext"></search-result>

None of the nothing-* values is evers shown.

Any ideas what's wrong?

The usage of you component is not correct. If you want to pass a string it should be quoted:

<search-result search-for="'nothing-ext'"></search-result>

Then next problem is that this line

<p>SearchResult for <span ng-model="$ctrl.searchFor"</span></span></p>

doesn't make sense, as ngModel directive is only valid for input controls. You want ngBind or simple {{ $ctrl.searchFor }} :

<p>SearchResult for <span ng-bind="$ctrl.searchFor"</span></span></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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