How to properly use the same AngularJS 1.5 component multiple times in a view?

后端 未结 2 1381
情书的邮戳
情书的邮戳 2021-01-26 09:46

I\'m creating a set of widgets with AngularJS 1.5\'s new components. The problem is, when using the same widget multiple times, they somehow share their controller or scope. I t

2条回答
  •  别那么骄傲
    2021-01-26 10:29

    The problem with your code is that you are declaring the $widget on window scope, that's why your controller prints the last value, bacause it was being overridden every time the controller was getting instantiated. Use a var $widget instead and your code will work fine.

    The following snippet solves this issue:

    angular.module('app', [])
      .component('widgetList', {
        templateUrl: 'template/widget/widget-list.html',
        bindings: {
          title: '@',
        },
        controllerAs: '$widget',
        controller: WidgetListController
      });
    
    function WidgetListController($timeout) {
    
      var $widget = this;
    
      console.log('Title on init: ', $widget.title)
    
      $timeout(function() {
        console.log('Title after 3 seconds: ', $widget.title)
      }, 3000)
    
      $widget.doSomething = function() {
        $widget.content = "Something";
      }
    }
    
    angular.element(document).ready(function() {
      angular.bootstrap(document, ['app']);
    });
    
    
    
    
    
    
    
    
    
    
    

提交回复
热议问题