Angular指令使用“=”作用域和controllerAs

3
我正在尝试编写一个指令来解码和编码一些信息。基本上,我正在使用一个Int(为每个位赋值16、8、4、2、1)将5个二进制信息存储在数据库中。
我需要两种编辑数据的方式:作为Int和作为位。但是我遇到了很多问题,它们(故意)通过使用controllerAs符号进行复合。
1) 当我更改Int时,位没有任何变化。这是因为链接函数似乎只加载了一次 - 如何使模型的更改更新指令中的信息?
<input ng-model="c.int" type="text" />
<testdir score="c.int"></testdir>

我的指令包括:

scope: {
  score: '='
},
controller: function() {
  var vm = this;
  vm.recChange = function() {
    // convert bits to score
  }
},
controllerAs: 'd',
link: function(scope, elem, attrs) {
  // convert score to bits

还有一个链接函数,将分数转换为scope.recommendations,它是一个5位数组。

2)当我改变这些位(并且控制器使用$scope)时,Int确实会改变。但是我找不到一种使用controllerAs的方法-链接函数使用scope,而我的控制器需要一个d.前缀。

template: "<label ng-repeat='(key, recommendation) in recommendations' class='checkbox-inline'>

// template: "<label ng-repeat='(key, recommendation) in d.recommendations' class='checkbox-inline'> \

Plnkr

2个回答

1
你必须使用scope.score,而不是使用score的属性值,因为你在作用域声明中使用了双向数据绑定符号=。此外,当某个值发生变化时,只需为该值放置观察器并在其中应用更改即可。
更新:只需将指令名称添加到指令定义的require键值中,你就可以在链接函数中将其作为第四个参数访问你的控制器。 FORKED PLUNKER
.directive('testdir', function() {
  var recommendationCategories = ['16RotM', '8Top5', '4Price', '2Cuisine', '1Area'];

  return {

    require: 'testdir',

    scope: {
      score: '='
    },

    controller: function () {
       // .....
    },

    controllerAs: 'd',

    link: function(scope, elem, attrs, ctrl) {

      console.log(ctrl);

      scope.$watch('score', function() {
        scope.recommendations = {};
        var score = parseInt(scope.score);
        // decode recommendations
        // convert to binary string
        var bitVal = score.toString(2);
        //pre-pad with "0"
        var e = recommendationCategories.length - bitVal.length;
        bitVal = "0".repeat(e) + bitVal;

        recommendationCategories.forEach(function (cat, idx) {
          scope.recommendations[cat] = {checked: (bitVal[idx]=="1") ? true : false};
        });

        // add a field for closed too
        scope.recommendations.closed = {checked : (score < 0)};
      });
    },
    template: "<label ng-repeat='(key, recommendation) in recommendations' class='checkbox-inline'> \
                <input type='checkbox' ng-model='recommendation.checked' ng-change='d.recChange()'/>{{key}} \
      -        </label>"
    // template: "<label ng-repeat='(key, recommendation) in d.recommendations' class='checkbox-inline'> \
  }

});

很好 - 这解决了问题的第一部分,但还有问题的第二部分。 - Simon H
它实际上在 $compile 文档中。 - ryeballar
抱歉,我仍然在努力将编码值 vm.score 从指令中传递回父级 http://plnkr.co/edit/PEWAzuPGJJleQqKW21Ds?p=preview。 - Simon H
除非我使用$scope,但我正在尝试弃用它。 - Simon H

1
在您的“controllerAs”值之后,需要添加bindToController:true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接