"Computed Properties" in AngularJS - angularjs

I recently chose AngularJS over ember.js for a project I am working on, and have been very pleased with it so far. One nice thing about ember is its built in support for "computed properties" with automatic data binding. I have been able to accomplish something similar in Angular with the code below, but am not sure if it is the best way to do so.
// Controller
angular.module('mathSkills.controller', [])
.controller('nav', ['navigation', '$scope', function (navigation, $scope) {
// "Computed Property"
$scope.$watch(navigation.getCurrentPageNumber, function(newVal, oldVal, scope) {
scope.currentPageNumber = newVal;
});
$scope.totalPages = navigation.getTotalPages();
}]);
// 'navigation' service
angular.module('mathSkills.services', [])
.factory('navigation', function() {
var currentPage = 0,
pages = [];
return {
getCurrentPageNumber: function() {
return currentPage + 1;
},
getTotalPages: function() {
return pages.length;
}
};
});
// HTML template
<div id=problemPager ng-controller=nav>
Problem {{currentPageNumber}} of {{totalPages}}
</div>
I would like for the UI to update whenever the currentPage of the navigation service changes, which the above code accomplishes.
Is this the best way to solve this problem in AngularJS? Are there (significant) performance implications for using $watch() like this? Would something like this be better accomplished using custom events and $emit() or $broadcast()?

While your self-answer works, it doesn't actually implement computed properties. You simply solved the problem by calling a function in your binding to force the binding to be greedy. I'm not 100% sure it'd work in all cases, and the greediness might have unwanted performance characteristics in some situations.
I worked up a solution for a computed properties w/dependencies similar to what EmberJS has:
function ngCreateComputedProperty($scope, computedPropertyName, dependentProperties, f) {
function assignF($scope) {
var computedVal = f($scope);
$scope[computedPropertyName] = computedVal;
};
$scope.$watchCollection(dependentProperties, function(newVal, oldVal, $scope) {
assignF($scope);
});
assignF($scope);
};
// in some controller...
ngCreateComputedProperty($scope, 'aSquared', 'a', function($scope) { return $scope.a * $scope.a } );
ngCreateComputedProperty($scope, 'aPlusB', '[a,b]', function($scope) { return $scope.a + $scope.b } );
See it live: http://jsfiddle.net/apinstein/2kR2c/3/
It's worth noting that $scope.$watchCollection is efficient -- I verified that "assignF()" is called only once even if multiple dependencies are changed simultaneously (same $apply cycle).
"

I think I found the answer. This example can be dramatically simplified to:
// Controller
angular.module('mathSkills.controller', [])
.controller('nav', ['navigation', '$scope', function (navigation, $scope) {
// Property is now just a reference to the service's function.
$scope.currentPageNumber = navigation.getCurrentPageNumber;
$scope.totalPages = navigation.getTotalPages();
}]);
// HTML template
// Notice the first binding is to the result of a function call.
<div id=problemPager ng-controller=nav>
Problem {{currentPageNumber()}} of {{totalPages}}
</div>

Note that with ECMAScript 5 you can now also do something like this:
// Controller
angular.module('mathSkills.controller', [])
.controller('nav', function(navigation, $scope) {
$scope.totalPages = navigation.getTotalPages();
Object.defineProperty($scope, 'currentPageNumber', {
get: function() {
return navigation.getCurrentPageNumber();
}
});
]);
//HTML
<div ng-controller="nav">Problem {{currentPageNumber}} of {{totalPages}}</div>

Related

Auto trigger function throuigh service in angularjs

hi all i am using angulrajs passing one value from one controller to another controller using service it's work fine but my need is when service value change in controller 2 i get the service value in one scope when scope value change i need trigger the function it's called refresh function when service value change and that i need to call the refresh function here my fiddle
https://jsfiddle.net/ctawL4t3/10/
You can just $watch your value.storeObject. Though it's not best of the practices, but it suits this kind of feature.
$scope.$watch('value.storedObject', function(newVal) {
if(newVal !== '') {
refresh()
}
})
working fiddle (open console to see refresh function logging)
You can try to use angular default $emit, $broadcast, or try to do 2 simple functions in own service
angular.module('app').factory('StoreService', function() {
var listeners = {};
var emit = function(name, val) {
if(listeners[name]) {
listeners[name](val)
}
}
var on = function(name, callback) {
listeners[name] = callback;
}
return {
emit: emit,
on: on,
storedObject: ''
};
});
JSFiddle example
JSFiddle example $watch
JSFiddle example ng-change is better because, you can use easily debounce
you can use broadcast function for that
Please check this SO link to find the related answer
How to call a function from another controller in angularjs?
app.controller('One', ['$scope', '$rootScope'
function($scope) {
$rootScope.$on("CallParentMethod", function(){
$scope.parentmethod();
});
$scope.parentmethod = function() {
// task
}
}
]);
app.controller('two', ['$scope', '$rootScope'
function($scope) {
$scope.childmethod = function() {
$rootScope.$emit("CallParentMethod", {});
}
}
]);

Updating Controllers/UI Elements In Angular

When working on a project, as these things tend to happen, we came across a situation where we were stumped on how to update certain UI elements when other things were done. For example, the navigation contains a counter of how many pending activities are due today. At any point in time during usage of the app, a user might schedule an activity for later today, and the count section would need to call the API to generate a count and the drop-down items associated with it.
How can I make a navigation controller pull the new list of activities when the main controller makes a change?
See this code for an example.
<div ng-app="TestApp">
<nav ng-controller="navigationController">
<p>The navigation count is: {{items.length}}</p>
</nav>
<div ng-controller="mainController">
<p>The main count is: {{items.length}}</p>
<p>
<button ng-click="addItem()" type="button">Add item.</button>
</p>
</div>
</div>
<script>
var app = angular.module('TestApp', []);
app.factory("api", function() {
return {
update: function() {
return ['a', 'b', 'c', 'd', 'e'];
}
};
});
app.factory("sharedFactory", function(api) {
var obj = {};
obj.items = ["a"];
obj.update = function() {
obj.items = api.update();
};
return obj;
});
app.controller("mainController", function(sharedFactory, $scope) {
$scope.items = sharedFactory.items;
$scope.addItem = function() {
sharedFactory.update();
};
});
app.controller("navigationController", function(sharedFactory, $scope) {
$scope.items = sharedFactory.items;
});
</script>
Our current solution was to create a callback service that other controllers could subscribe to, and then when an activity was created have those callbacks run as needed. This works nicely, but I'm nervous that I'm "doing it wrong".
We're switching to the Angular UI Router, now, so I'm curious if there's a better way of doing so in it. Right now our navigation handler is a stateless controller that hooks into our callback service still.
A nice way to handle this could be to use $scope.$on to listen for events, and $scope.$emit to fire an event going up the scope or $scope.$broadcast to fire an even going down the scope.
In each piece of the UI that needs to be updated can be listening with $scope.$on and update itself when an event is fired, like your user scheduling an event for later today.
Angular docs for $on, $emit and $broadcast
Though I generally think that registering scope values on a controller with a service is the best way to accomplish another option would be to use a factory and set a property of that on scope.
angular.module('app').factory('myService', function() {
var myService = {};
service.count = 0;
/// other service functions
return myService;
}
angular.module('app').controller('myController', function(myService) {
this.count = myService.count;
}
However you feel about MVC, you could use angular's internals to automatically do this:
https://jsfiddle.net/gkmtkxpm/
var myApp = angular.module('myApp', []);
myApp.factory('counter', function() {
return {
count: 0
};
});
myApp.controller('CounterController', function (counter) {
var vm = this;
vm.counter = counter;
vm.increment = function() {
vm.counter.count = vm.counter.count + 1;
};
});
edit:
Concerning your updated question, see the updated fiddle:
https://jsfiddle.net/gkmtkxpm/1/

Unsure why changes to a factory property are not being pushed to the page

This is a simplistic example of a problem I am having. I am clearly missing something in my understanding of Angular.
A Plunker is here: http://plnkr.co/edit/VLqA22dDTgk5PyPlCOGH?p=preview
And a copy-paste of the pertinent bits below:
<div ng-controller="myController">
<div>message: <label ng-model="message"></label></div>
<div></div><button ng-click="start()">Get Message</button></div>
</div>
var app = angular.module("app", []);
app.service('GetMessage', function() {
var message;
var start = function () {
this.message = 'Hello World';
};
return {
message: this.message,
start: start
}
});
app.controller('myController', function ($scope, GetMessage) {
$scope.message = GetMessage.message;
$scope.start = function () {
GetMessage.start();
console.warn('started..');
};
});
I would expect that the label directive would be 2-way bound to the factory's message property, so that when the start() function is called and the message is updated, that the page would be too.
To update the label in this way, do I need to broadcast an event to $rootScope, listen for it in the controller, and then update the label? It seems a very manual way of doing it.. surely there is a better way.
Thank you.
You are currently using a primitive data type, which means the following line will copy the value into a new variable:
$scope.message = GetMessage.message;
Updating one will not affect the other.
An easy solution is to use an object instead:
var message = { value: '' };
var start = function() {
message.value = 'Hello World';
};
And:
$scope.message = GetMessage.message;
Now the reference to the object would be copied into a new variable instead and both would refer to the same object.
Another issue is that you are using ngModel on a label to display the value, which will not work. ngModel is normally used on input, select and textarea elements.
You can instead use ng-bind:
<label ng-bind="message.value"></label>
Or the less verbose shortcut:
<label>{{message.value}}</label>
Demo: http://plnkr.co/edit/rUgN94DAIOfQGI8tr9kl?p=preview
If you prefer to keep using primtive values you need to handle it another way. For example by using events like you mentioned. Another solution is to register a watcher to watch for changes and update the scope variable:
app.controller('myController', function($scope, GetMessage) {
var watchExpression = function() {
return GetMessage.message;
};
var listener = function(newValue, oldValue) {
if (newValue === oldValue) return;
$scope.message = newValue;
}
$scope.$watch(watchExpression, listener);
$scope.start = function() {
GetMessage.start();
console.warn('started..');
};
});
Demo: http://plnkr.co/edit/klSl1DCUlQI3Z5ih16sq?p=preview

AngularJs Directive does not intercept the updates of the services

I am trying to implement the directive that is consuming the data from the service and reacts accordingly. However, something is going wrong and I need some assistance.
Here is the sample of the code that also can be found at http://jsfiddle.net/3c9h7/5/
var app = angular.module('myApp', []);
app.service('MyService', [
'$rootScope', function($rootScope) {
this.value = 4;
var self = this;
function inc(){
self.value += 3;
}
setInterval(inc, 1000);
}
]);
app.directive('myDir', ['MyService', function(MyService){
return {
link : function(scope, element){
function expr(){
return MyService.value;
}
function react(){
element.html(MyService.value);
}
scope.$watch(expr, react);
react();
}
}
}]);
<div ng-app='myApp'my-dir>
</div>
As the result Div element displaying the initial value of MyService.value but is ignoring the updates that happens in the service every second.
I have found the solution which involves rootScope(i.e. uncomment lines 7 and 9 in the jsFiddle sample):
function inc(){
$rootScope.$apply(function(){
self.value += 3;
});
}
setInterval(inc, 1000);
However, it does seem to be right to me..All the samples I found are not using this trick..So, am I missing something? Is "rootScope" solution appropriate? Maybe there is a better way to achieve the goal?
Thanks!
Use Angular's $interval (ref) instead of window.setInterval().
What it does though is actually calling apply() under the hoods, so your solution is correct, just a bit more complex. Also $interval can be mocked for testing.

How to reuse one controller for 2 different views?

I have defined one controller, and apply it to 2 views with small differences.
Angular code:
app.controller('MyCtrl', function($scope) {
$scope.canSave = false;
$scope.demo = {
files : [{
filename: 'aaa.html',
source: '<div>aaa</div>'
}, {
filename: 'bbb.html',
source: '<div>bbb</div>'
}]
}
$scope.newFile = function(file) {
$scope.demo.files.push(file);
}
$scope.$watch("demo.files", function(val) {
$scope.canSave = true;
}, true);
});
View 1:
<div ng-controller="MyCtrl"></div>
View 2:
<div ng-controller="MyCtrl"></div>
The sample code is very simple, but there are a lot of code and logic in my real project.
The View 1 and 2 have almost the same features, only with a few differences, but I do need to write some code for each of them in the controller.
I don't want to create 2 different controllers for them, because they have most of same logic. I don't want to move the logic to a service to share it between the 2 controllers, because the logic is not that common to be a service.
Is there any other way to do it?
Under the given conditions I might be doing something like
function MyCommonCtrl(type){
return function($scope, $http) {
$scope.x = 5;
if(type = 't1'){
$scope.domore = function(){
}
}
....
....
}
}
angular.module('ng').controller('Type1Ctrl', ['$scope', '$http', MyCommonCtrl('t1')]);
angular.module('ng').controller('Type2Ctrl', ['$scope', '$http', MyCommonCtrl('t2')]);
Then
<div ng-controller="Type1Ctrl"></div>
and
<div ng-controller="Type2Ctrl"></div>
I don't know your specific set-up but your 2 controllers could inherit from a common ancestor.
Type1Ctrl.prototype = new MyCtrl();
Type1Ctrl.prototype.constructor = Type1Ctrl;
function Type1Ctrl() {
// constructor stuff goes here
}
Type1Ctrl.prototype.setScope = function() {
// setScope
};
Type2Ctrl.prototype = new MyCtrl();
Type2Ctrl.prototype.constructor = Type2Ctrl;
function Type2Ctrl() {
// constructor stuff goes here
}
Type2Ctrl.prototype.setScope = function() {
// setScope
};
I also faced similar problem and scope inheritance solved my problem.
I wanted to "reuse" a controller to inherit common state/model ($scope) and functionality (controller functions attached to $scope)
As described in the "Scope Inheritance Example" I attach parent controller to an outer DOM element and child controller to the inner. Scope and functions of parent controller "merge" seamlessly into the child one.
Here is another option. Slightly modified from this blog post
app.factory('ParentCtrl',function(){
$scope.parentVar = 'I am from the parent'
};
});
app.controller('ChildCtrl', function($scope, $injector, ParentCtrl) {
$injector.invoke(ParentCtrl, this, {$scope: $scope});
});
here is a plunker

Resources