Angular Directive using '=' scope & controllerAs
I am trying to write a directive to decode and encode some information. Basically I store 5 binary chunks of information in a database using Int (giving each bit a value of 16, 8, 4, 2, 1).
I need ways to edit data: both Int and like bits. But I have a lot of problems with them and they are (intentionally) exacerbated by notation for controllers.
1) When I change Int, nothing changes in the bits. This is because the link function is only loaded once - how can I change the model update information in the directive?
<input ng-model="c.int" type="text" />
<testdir score="c.int"></testdir>
My Directive includes:
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
and a link function that converts the count to scope.recommendations
, which is an array of 5 bits.
2) When I change bits (and have controllers using $ scope) then Int changes. But I can't seem to find a way to use controllerAs - the link function uses scope
, whereas my controller needs a prefix d.
.
template: "<label ng-repeat='(key, recommendation) in recommendations' class='checkbox-inline'>
// template: "<label ng-repeat='(key, recommendation) in d.recommendations' class='checkbox-inline'> \
source
You should use scope.score
the evaluation attribute value instead, since you are using two-way data binding =
in the scope declaration for the evaluation. Also, when changes for a specific exist, just set an observer for that value and apply your changes to it.
UPDATE . Just add your directive name to the key value of require
your directive definition and you can access your controller in your bind function as the fourth argument.
.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'> \
}
});
source