假设我正在使用一个表示字符串值的类(更像是一种结构),其副作用是每次访问它时都会更改其值:
function Foo() {
var value = 'a';
this.getValue = function() {
if (value == 'a') {
value = 'b';
return 'a';
}
else {
value = 'a';
return 'b';
}
}
}
..我覆盖它的toString()
方法:
Foo.prototype.toString = function() {
return this.getValue();
}
使用直接参考输出此值很好:
var foo = new Foo();
alert(foo); //a
document.getElementById('bar').innerHTML = foo; //b
但是,输出带有AngularJS表达式的对象会导致显示{}
而不是toString()
/ getValue()
值:
var foo = new Foo();
var app = angular.module('main', []);
app.controller('ctrl', function($scope) {
$scope.val = foo;
alert($scope.val); //a (has not been changed by previous line)
});
..然后:
<div ng-app="main" ng-controller="ctrl">{{val}}</div> //{} (rather than b)
我可以使用$scope.val = foo.getValue();
,$scope.val = foo.toString();
甚至$scope.val = foo + '';
,并根据Is it possible to provide an implicit way of converting object into string for angular templates? ng-bind
调用toString()
方法,但为什么当Angular评估表达式中的对象时,它是否被调用?