Angular 1.5组件中的$ compile抛出$ .watch不是函数错误

时间:2016-08-02 09:09:02

标签: angularjs angularjs-directive components

我正在将directive迁移到component结构,一切都很顺利 - 除了我有动态模板,我正在动态编译。工作正常,除非我尝试将ctrl传递给$ compile:

我改变了:

$compile($element.contents())($scope);

正在努力:

$compile($element.contents())(ctrl);

现在我收到了这个错误:

child-component.component.js:76 TypeError: b.$watch is not a function
    at Object.link (http://localhost:3000/lib/angular/angular.min.js:302:155)
    at http://localhost:3000/lib/angular/angular.min.js:16:56
    at ja (http://localhost:3000/lib/angular/angular.min.js:81:35)
    at m (http://localhost:3000/lib/angular/angular.min.js:66:274)
    at g (http://localhost:3000/lib/angular/angular.min.js:58:481)
    at g (http://localhost:3000/lib/angular/angular.min.js:58:498)
    at g (http://localhost:3000/lib/angular/angular.min.js:58:498)
    at g (http://localhost:3000/lib/angular/angular.min.js:58:498)
    at http://localhost:3000/lib/angular/angular.min.js:58:119
    at http://localhost:3000/js/components/component-group/child-component.component.js:76:54

这是一个带有一些ctrl的元素的例子,因为我怀疑这个问题与绑定有关。

<div class="box" ng-class="{selected:ctrl.selected == 1}" ng-show="ctrl.selected"> 

这是我的组件声明:

var childComponent = {
    controllerAs: 'ctrl',
    require: 'parentComponent',
    bindings: {
        attrone: '<',
        attrtwo: '<'
    },
    controller: childComponentController
};

function childComponentController(SomeFactory, $rootScope, $compile, $timeout, $element, $scope) {
etc...

我在迁移时遇到了什么问题?

1 个答案:

答案 0 :(得分:0)

这是我如何整理你的组件以解决任何语法问题。

成分:

var childComponent = {
  require: {
    parent: '^parentComponent'
  },
  bindings: {
    attrOne: '<',
    attrTwo: '<'
  },
  controller: function() {
    var vm = this;

    vm.$onInit = function() {
      console.log('Parent:', vm.parent);
    }
  }
};
  • 使用对象语法
  • 将父级分配给控制器
  • 使用“^”搜索同一级别或更高级别的父级控制器。
  • camelcase你的绑定属性
  • 更新视图以使用本机$ctrl命名空间

查看:

<div class="box" ng-class="{ 'selected': $ctrl.selected === 1 }" ng-show="$ctrl.selected">

我也相信你的$ compile不应该改变。 $ compile应该使用$ scope。尝试将其重新设置为$compile($element.contents())($scope);

如果您能够使用codepen或类似软件进行复制,我将很乐意为您提供有关该问题的报告。