我想将Angular模型绑定到Knockout组件。它正在工作 - 当Angular模型更改Knockout绑定时适用。但问题的方向相反 - 我希望Angular模型在Knockout组件更改时进行更新,并且在不触及组件的情况下(它不必知道Angular包装器)。 目标 - 使用Angular在KO组件周围构建一个快速原型框架,该组件正在其他环境中使用。 KO组件可以并应该共享模型(来自Angular wrapper),因此这个问题。Angular - Knockout模型共享
编辑: 这是一个jsFiddle示例来展示我想要达到的目标。 它是一种简化,因为在现实世界中,KO组件将使用内部虚拟机,这将难以收看。但即使在这里,我也不明白为什么$ watch不起作用。
var sharedData = {
personName: "alex",
personAge: "32"
};
function WrapperCtrl($scope){
$.each(sharedData, function(key, value) {
sharedData[key] = (typeof value !== "function") ? ko.observable(value) : value;
});
$scope.wrapData = sharedData;
ko.applyBindings(sharedData, document.getElementById("ko_1"));
ko.applyBindings(sharedData, document.getElementById("ko_2"));
$scope.$watch(
function() {
return sharedData.personName();
},
function(newValue, oldValue) {
console.log("change");
}
);
$scope.doSomething = function(){
console.log("before angular function: ", $scope.wrapData.personName(), $scope.wrapData.personAge())
sharedData.personName('Bob').personAge(41);
console.log("after angular function: ", $scope.wrapData.personName(), $scope.wrapData.personAge())
};
}
function doSomething() {
console.log("before knockout function", sharedData.personName(), sharedData.personAge())
sharedData.personName('Mary').personAge(25);
console.log("after knockout function", sharedData.personName(), sharedData.personAge())
}
请做出的jsfiddle例子或张贴一张你的代码。 – frkk
这里是小提琴:http://jsfiddle.net/HmcnB/10/ – krulik