什么是AngularJS计算观察到了淘汰赛的可写的模拟? [英] What is the analog for Knockout's writable computed observable in AngularJS?
问题描述
我用KnockoutJS在我的项目,但要学会AngularJS,因为它有很多好吃的功能,淘汰赛没有。
所以我感兴趣的重写采用了棱角分明一些我的code的。但我不知道该怎么办,我在淘汰赛使用一些简单的事情。
例如,淘汰赛有计算观测的一个特点。这个很酷!
我已经发现,我可以用一个简单的函数。但淘汰赛提供了写的功能,它向计算观测,如:
I use KnockoutJS in my projects, but want to learn AngularJS as it has a lot of tasty features that Knockout doesn't have. So I'm interested in rewriting some of my code using Angular. But I don't understand how to do some simple things that I use in Knockout. For example, Knockout has a feature of computed observables. It's cool! I've already found that I can use a simple function instead. But Knockout provides "write" function to a computed observables, like:
var first_name = ko.observable('John'),
last_name = ko.observable('Smith'),
full_name = ko.computed({
read: function(){
return first_name() + ' ' + last_name();
},
write: function(new_value){
var matches = new_value.match(/^(\w+)\s+(\w+)/);
first_name(matches[1]);
last_name(matches[2]);
}
});
在此的jsfiddle code: http://jsfiddle.net/Girafa/QNebV/1/
This code on JSFiddle: http://jsfiddle.net/Girafa/QNebV/1/
这code可让我当我改变FULL_NAME一更新FIRST_NAME和姓氏观测。如何它可以使用AngularJS做什么?正在检查生存与参数的函数?像这样的事情?
This code allows me to update the "first_name" and "last_name" observables when I change the "full_name" one. How it can be done using AngularJS? A function with an argument being checked for existence? Something like this?
first_name = 'John';
last_name = 'Smith';
full_name = function(value){
if (typeof value != 'undefined')
{
// do the same as in the Knockout's write function
}
else
{
// do the same as in the Knockout's read function
}
}
什么是最好的做法是什么?
What is the best practice?
推荐答案
我已经找到这样的解决方案:的http://的jsfiddle。净/ Girafa / V8BNc /
I've found such a solution: http://jsfiddle.net/Girafa/V8BNc/
而是采用了棱角分明$表的方法,我们设置本地JavaScript fullName属性的getter和setter:
Instead of using angular $watch method, we set native javascript getter and setter of the fullName property:
Object.defineProperty($scope, 'fullName', {
get: function(){
#...
},
set: function(newValue){
#...
}
})
想到这是我不需要做任何特殊的观察家在code更方便。但我不知道浏览器支持这种解决方案的。
Think this is more convenient as I don't need to make any special watchers in the code. But I don't know about browser support of this solution.
这篇关于什么是AngularJS计算观察到了淘汰赛的可写的模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!