I am in need of a Factory object that can be linked with a $scope.property to produce a certain result. Additionally, I require the ability to detect changes in either the modifier within the factory instance or the $scope.property in order to update the result. It is possible that my understanding of this pattern could be flawed.
app.factory('MyFactory',
function () {
var MyFactory = function (name, modifier) {
this.name = name;
this.result = 0;
this.modifier = modifier;
}
//I may want to invoke this method when the modifier or MyProperty changes
MyFactory.prototype.modifyingMethod = function () {
this.result = this.modifier * //externalProperty;
}
MyFactory.prototype.watcher = function () {
//uncertain about the purpose of this method or if it's necessary at all
// A recalculation of the result similar to using $watch is needed here
this.modifyingMethod();
}
return MyFactory;
}
)
app.controller('MyCtrl'
function($scope, MyFactory) {
$scope.MyProperty = 42;
$scope.MyFactoryOptions = [
new MyFactory('Option1', 1),
new MyFactory('Option2', 2),
new MyFactory('Option3', 3),
new MyFactory('Option4', 4),
new MyFactory('Option5', 5)
];
}
The challenge lies in monitoring both MyProperty and the modifier (potentially altered by users) through $watch to update the result accordingly. When the Property is a value type, passing it into the Factory constructor might not suffice. One solution could be passing a function that returns MyProperty.
Is it feasible to implement an internal $watch within the factory? If done externally, in the controller, a separate watch would be required for each instance. Would establishing a register method on the factory object be a better approach?
Any suggestions for patterns or alternative methods that could prove useful in this scenario?