2015-05-10 56 views
3

我試圖編寫一個指令來解碼和編碼一些信息。基本上我使用一個Int將5個二進制信息存儲在一個數據庫中(給每個位賦值16,8,4,2,1)。Angular Directive使用'='scope&controllerAs

我需要編輯數據的方式:作爲一個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

回答

1

你必須使用scope.score,而不是因爲你使用的雙向數據爲得分的範圍內聲明綁定的符號=使用得分的屬性值。此外,如果某個特定變化存在,則只需將觀察者放入該值並在其中應用更改即可。

UPDATE:只需在您的指令定義的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'> \ 
    } 

}); 
+0

大 - 這解決了第1部分,但留下一個問題 –

+0

的第2部分請檢查我更新 – ryeballar

+0

哇 - 謝謝。很高興這不是微不足道的 –

1

你的 「controllerAs」 你需要添加bindToController值後:真