In Angular, a key feature is the two-way binding which keeps the model always up to date. However, I have a situation where I have what is essentially a dependent property of a model. My question is about how to implement it. I can insert an expression into the view to display a calculation that depends on elements of the model, but I would like to have that expression assigned as a field in the model, such that other expressions could then use that result with everything updating nicely.
A simple example might have fields a, b, and c in the model, with c = a * b. It's possible to put {{a * b}} into the view but, I'd rather have a field for c such that I could reference c in other expressions and simply use {{c}} in the view where I need it displayed, with c updating whenever a or b are updated.
I guess you could put a watch on a and b and recalculate c, but it seems like the machinery is already in Angular somewhere to have that done automagically, since it works for expressions in the view. If I don't know the expression ahead of time (and I won't) I'd need to parse the expression for c to pull out variables and set up watches on all of them... surely with Angular there is a better way.
Can one do something like put an Angular expression into a model?
I understand that there is a danger here - you could create a self-referential loop, but that would be detectable such that an error could be thrown.
Knockout has concept of computableObservable but angular has no such different thing. However you can do something like below. It would automatically change the value of c when a has changed. Look at below code snippet.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.a=5;
$scope.b=10;
$scope.c = function(){return $scope.a*$scope.b}
$scope.changea = function(){$scope.a = 25}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{c()}}
<input type="button" value="change a value to 25" ng-click="changea()" />
a = {{a}}
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With