Angular Directive使用' ='范围& controllerAs

时间:2015-05-10 06:25:27

标签: angularjs

我试图编写一个指令来解码和编码某些信息。基本上我使用Int将5个二进制信息存储在数据库中(每个位的值为16,8,4,2,1)。

我需要编辑数据的方法:作为Int和bit。但是我在连接它们时遇到了很多问题,这些都是(故意)使用控制器符号表示的。

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 个答案:

答案 0 :(得分:1)

您必须使用scope.score而不是使用分数的属性值,因为您在范围声明中使用双向数据绑定表示法=来获得分数。此外,当存在某种变化时,只需将观察者放置在该值并在其中应用您的更改。

更新:只需在指令定义的require键值中添加指令名称,就可以在链接函数中访问控制器作为第四个参数。< / p>

<强> 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'> \
  }

});

答案 1 :(得分:1)

在你的&#34; controllerAs&#34;你需要添加 bindToController:true

的值