我试图将一些简单的数值参数传递到自定义指令中。(我一直从柱塞那里得到连接超时,所以请容忍我。)
<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的值,却得到了recordCount的0?两者都以相同的方式声明、通过、绑定和报告。我已经用我所知道的每一种方式来跳舞。只有使用"@"和$observe,我才能为recordCount获得正确的值,但是pageSize可以按原样工作。
发布于 2014-05-14 03:11:30
在您提供的代码之外,还必须发生其他导致scope.recordCount为0的事情。您的代码看起来很好,我几乎肯定,如果您把它扔进小提琴里,recordCount将是53岁。但是,在totalPages计算中存在一个问题。将返回属性内部的原始值,即字符串“记录计数”。您需要的是$evaluated值。你可以用范围手动的$evaluate它.
attrs.$observe("recordCount", function(recCt) {
console.log("OBSERVER: recCt", scope.$eval(recCt));
scope.totalPages = calcPages(scope.$eval(recCt), scope.pageSize);
});虽然我会用范围。
scope.$watch("recordCount", function(recCt) {
console.log("OBSERVER: recCt", recCt);
scope.totalPages = calcPages(recCt, scope.pageSize);
});https://stackoverflow.com/questions/23641134
复制相似问题