我试图将一些简单的数字参数传递给自定义指令。 (我一直在从Plunker获得连接超时,所以请耐心等待。)
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);
});
}
};
}
]);
现在,我知道有几个红旗。我的简单数字可能应该已经被内插(例如,record-count="{{recordCount}}"
)并且被绑定为字符串(例如,recordCount: "@"
)。我试过了,这就是为什么你会看到$observe
功能的原因。在找到this great answer之前,我花了很长时间才弄明白。
无论如何,在上面的示例中,为什么scope
正确获取pageSize
的值,但0
得到recordCount
?两者都以相同的方式声明,传递,绑定和报告。我知道如何以各种方式跳舞。仅使用"@"
和$observe
,我才能获得recordCount
的正确值,但pageSize
按原样运行。
答案 0 :(得分:1)
你提供的代码之外的其他东西必须在导致scope.recordCount为0的情况下进行。你的代码看起来很好,而且我几乎是正数,如果你把它放在小提琴中,则recordCount将为53。但是,您的totalPages计算存在问题。 attrs。$ observe将返回属性内的原始值,即字符串&#39; recordCount&#39;。您想要$ evaluate值。您可以使用范围手动评估它。$ eval ...
attrs.$observe("recordCount", function(recCt) {
console.log("OBSERVER: recCt", scope.$eval(recCt));
scope.totalPages = calcPages(scope.$eval(recCt), scope.pageSize);
});
虽然我会使用范围。$ watch ...
scope.$watch("recordCount", function(recCt) {
console.log("OBSERVER: recCt", recCt);
scope.totalPages = calcPages(recCt, scope.pageSize);
});