I'm trying to pass some simple, numeric parameters into a custom directive. (I keep getting connection timeouts from Plunker, so please bear with me.)
HTML
<body ng-controller="MainCtrl">
<custom-page-selector
record-count="recordCount"
page-size="pageSize"
page-number="pageNumber"
></custom-page-selector>
</body>
JS
// AngularJS v1.2.16
app.controller('MainCtrl', function($scope) {
$scope.pageSize = 20;
$scope.recordCount = 53;
$scope.pageNumber = 1;
});
app.directive("customPageSelector", [
function () {
function calcPages (recordCount, pageSize) {
console.log("dividing " + recordCount + " by " + pageSize);
return Math.ceil(recordCount / pageSize);
}
return {
template: "<pre>\
<p>recordCount = {{recordCount}}</p>\
<p>pageSize = {{pageSize}}</p>\
<p>pageNumber = {{pageNumber}}</p>\
</pre>",
replace: true,
restrict: "E",
scope: {
recordCount: "=",
pageSize: "=",
pageNumber: "="
},
link: function(scope, element, attrs) {
console.log("LINK: scope", scope);
console.log("LINK: scope.recordCount", scope.recordCount); // logs "0"
console.log("LINK: scope.pageSize", scope.pageSize); // logs "20"
attrs.$observe("recordCount", function(recCt) {
console.log("OBSERVER: recCt", recCt);
scope.totalPages = calcPages(recCt, scope.pageSize);
});
}
};
}
]);
Now, I know there are a couple of red flags. My simple numbers should probably be passed-in already interpolated (e.g., record-count="{{recordCount}}"
) and bound as strings (e.g., recordCount: "@"
). I have tried that, and that's why you'll see the $observe
function. I spent long enough trying to figure that out before finding this great answer.
Regardless, in the above example, why does scope
correctly get the value of pageSize
, but gets 0
for recordCount
? Both are declared, passed, bound and reported the same way. I have danced around this every way I know how. Only using "@"
and $observe
have I been able to get the correct value for recordCount
, but pageSize
works as-is.