Angular UI TimePicker Bi-Directional Behaviour - angularjs

I would like to know which parte of the directive source code I should modify in order to implement bi-directional behaviour with this component ?. Because upon certain conditions, I should change the time to "08:00" or leave it like it is... I saw that an isolated scope is implemented so maybe that explains the behavuour...
Thankx

The ng-model attribute on your timepicker (if it exists), represents the bound data point exposed for you to change, and be changed by this directive.
<timepicker ng-model='scopeVariableYouBindToDatePickerToHaveAccessToSelectedValue' />
If you have an example of the source code, or the directive itself, please feel free to post an example or link.

Not fully sure I understand, but here goes nothing...
$scope.update = function() {
var d = new Date();
d.setHours( 8 );
d.setMinutes( 0 );
$scope.mytime = d;
};
OR better if you do not want to have to click a button, but this watch would have to be tied to some event of course:
$scope.$watch('something_to_watch', function(new, old) {
var d = new Date();
d.setHours( 8 );
d.setMinutes( 0 );
$scope.mytime = d;
});
And as Sean Larkin said, your html would then look like this:
<timepicker ng-model='{{mytime}}' />

Related

TinyMCE + AngularJS - Keyup event triggered before update of ng-model

I am fairly new to AngularJS and the TinyMCE editor. I was fiddling around with the keyup event available in TinyMCE when I came across this issue. In the keyup handler, I am accessing one of the controller's ng-model. Here's where things start to get odd. I printed out the ng-model value and the editor's content for comparison purposes and it would seem that the ng-model is lagging by 1 key/character behind i.e. the editor's content is the most up to date. I have a hunch that the model is updated only after the keyup event is finished. That would explain why I am seeing two values here. Perhaps I am going about this the wrong way? Speaking of which, what would be the best/correct way to access the editor's contents? Through angular or TinyMCE?
If it helps, the code looks something like this (They are placed under a single controller):-
...
this.text = "";
var viewModel = this;
this.tinymceOptions = {
setup: function (editor) {
editor.on('keyup', function (e) {
console.log(editor.getContent());
console.log(viewModel.text);
});
},
...
};
Has anyone encountered this problem before?
Thanks for the help in advance!

What is the right way to select by value in a dropdown?

I'm having a bit of an issue with Angular and selecting an item from a dropdown and making Angular update the model.
I've been searching through StackOverflow, but only with partial luck.
The problem is that when i'm manually setting a value on a model, my dropdown updates correct, but the model itself does not update;
$scope.setSelected = function(){
$scope.selected.id = 15;
//$scope.$apply();// $apply already in progress
}
From various answers on StackOverflow, I've found out that Angular does not know about this update and the suggested answer is to run either a $scope.$apply() or a $scope.$digest(), but both throw a $apply already in progress exception. I have a feeling that this is not the correct way for me to do it, since it doesn't make sense, that you have to trigger an event to select by value.
What is the correct way to select an item in a dropdown by a given value?
Full code example can be found at https://jsfiddle.net/c2x3jvut/
When clicking the "Select dinnerman" button, the dropdown updates correct, but the shown model and when clicking "Log selected" it only shows the selected model, but with an updated id.
You can use $filter to get whole object instead of each property.
$scope.setSelected = function(){
$scope.selected = $filter('filter')($scope.persons,15,'id')[0];
//$scope.selected.id = 15;
//$scope.$apply();// $apply already in progress
}
Here is the modified version
ng's select binds its value based on its ngModel, which is being manipulated incorrectly in the example. The correct method is to change the reference of the ngModel rather than the select's id:
$scope.setSelected = function () {
$scope.selected = $scope.persons[1]; // yes
// $scope.selected.id = 15; // no
};
Fiddle might have been updated to show the effects.
Not sure I understand your question, but still...
You may include in each entry of the dropdown:
...ng-click="setSelected(<value>)"...
and, of course, add a parameter to the function.
By the way, are you aware that in the fiddle example you are selecting ID 15 in function setSelected?
You are just updating the current model with an ID. But when you see carefully the name and age remains same. Further you need to update the whole object as below:
$scope.setSelected = function(){
$scope.selected.id = 15;
$scope.selected.name = "Dinner-man";
$scope.selected.age = 20;
}
Or anyother way to directly updates the object.

Angularjs form.$dirty

I'm able to find form data is changed or not using $dirty.
ex: I changed text box or drop down and then $dirty become true. If I reverted to old data still it is true. I need to know if my changes are reverted or not. Do we have any property in Angularjs? If property is true I want to enable save button otherwise it should be disable.
https://docs.angularjs.org/api/ng/type/form.FormController
I need to implement around 10 pages and each page has 10 text boxes and a couple of drop downs. So I don't want track each control manually in my pages.
You can try using this module: https://github.com/betsol/angular-input-modified
From the README file:
This Angular.js module adds additional properties and methods to the
ngModel and ngForm controllers, as well as CSS classes to the
underlying form elements to provide end-user with facilities to detect
and indicate changes in form data.
This extra functionality allows you to provide better usability with
forms. For example, you can add decorations to the form elements that
are actually changed. That way, user will see what values has changed
since last edit.
Also, you can reset an entire form or just a single field to it's
initial state (cancel all user edits) with just a single call to the
reset() method or lock new values (preserve new state) just by calling
overloaded $setPristine() method.
DISCLAIMER: I haven't tried it myself and I notice the author overwrites the ngModel directive instead of adding a decorator, which could be dangerous...but at the very least, you can look at the source and get an idea of how to write your own service or directive with similar functionality.
Even though it does not follow the usage of $dirty, but an implementation similar to this might be helpful for you in the case of a Save button on update.
Inside your html:
<form name="testForm" ng-controller="ExampleController" ng-submit=" save()">
<input ng-model="val" ng-change="change()"/>
<button ng-disabled="disableSave">Save</button>
</form>
Inside your controller:
.controller('ExampleController', ['$scope', function($scope) {
$scope.disableSave = true; // Keep save button disabled initially
$scope.val = 'Initial'; // Initial value of the variable
var copyVal = $scope.val; // Copy Initial value into a temp variable
$scope.change = function() {
$scope.disableSave = $scope.val === copyVal;
};
$scope.save = function() {
// Save the updated value (inside $scope.val)
console.log($scope.val);
// Re-disable the input box (on successful updation)
copyVal = $scope.val;
$scope.disableSave = true;
};
}]);
Here is a working plunkr for the same.

New to Angular - Computed Variables

I am moving to Angular from Knockout, and I have a few issues. I'm assuming that I must be doing something a non-angular type of way.
http://jsfiddle.net/LostInDaJungle/BxELP/
I linked to jsfiddle so I didn't have to include my code here
Stack Overflow will not let me post my question without a code block.
Here is a very basic fiddle that outlines two of my major problems...
Problem 1: val1 and val2 are initialized as 3 and 4, and add up to 7 properly. However, if you change either of the values in the text boxes, the new value is treated as a string and I get concatenation instead of addition. Change val1 to 4 and you get 44 when it should be 8. What is the best way around this behaviour?
Problem 2: Calculated fields. I can get a calculated field by using the curly brackets like {{val1 + val2}} and have the calculated fields auto update when the underlying model changes, but this is totally unacceptable. In my full fledged app, we generate a "cost" that is used several times throughout and having to put in the cost calculation each and every time is a pain. Not to mention that when this calculation changes, I now have the unenviable task of finding 15 different places that use the cost calculation and updating them all.
In addition, if I try to put an ng-model="cost" on the input with the curly brackets, then the curly brackets don't work. So nothing jumps out at me as a way to bind cost.
http://jsfiddle.net/LostInDaJungle/QNVwe/
This example is more like the structure I desire. However, unlike a ko.observable, the calculated fields do not update when the values that generate them change. The boilerplate solution everyone has foisted on me is to write a bunch of ng-change handlers... But that is awful. If width changes change the cost and change the payback calculations, etc... It quickly becomes a tangled mess.
Both of these methods fail as far as separating logic from presentation. Method one has my business logic embedded in my HTML. Method two puts a whole bunch of ng-change handlers in my code which isn't that much different from having to write a whole mess of onChange handlers in plain ol' HTML. If I HAVE to do a bunch of ng-change handlers, I would just as soon do an onChange handler in Javascript because I can at least declare them outside of my presentation layer.
Here's a knockout version of the same:
http://jsfiddle.net/LostInDaJungle/eka4S/2/
This is more like what I would expect... Nothing but data-binds on my inputs, all program logic nicely contained within the view model. Also, since my computable is a Javascript function, I don't have to scratch my head about how to ensure my two values are numeric.
So....
Computed variables: Is there a way to watch the underlying variables and update the computed amount automatically? Without having to bury my program logic in my HTML?
Is there a good way to keep my numbers from turning into strings?
Thank you for your help.
FYI, also posted to Google Groups: https://groups.google.com/forum/#!topic/angular/0dfnDTaj8tw
For a calculated field, add a method to your controller . . .
$scope.cost = function() { return $scope.val1 + $scope.val2 };
and then bind to it directly. It will know when it needs to recalculate as its constituent values change.
<div>{{cost()}}</div>
Ok,
A few hours later and I think I have my answer.
Using $scope.$watch.
$scope.$watch('(height * width) * 40', function(v) {$scope.cost = v;});
or
$scope.$watch('height + width', function() {$scope.cost = (Number(height) * Number(width)) * 40;});
This auto-updates any computables for watched variables. And it gives me a way to work with these without having to live inside curly brackets.
Also, the computed values can be reused and tracked for cascading updates:
$scope.$watch('height * width', function(v) {$scope.dim = v;});
$scope.$watch('dim * 40', function(v) {$scope.cost = v;});
So if height and/or width change, dim is updated, and since dim has changed, cost is updated.
I changed your third input to:
<input type="text" value="{{val1 * 1 + val2}}" />
which causes Angular.js to treat the values as numbers, not strings.
Here is the fiddle. I gleaned the answer from here.
About problem 1:
You should use input type="number" if possible. That would take care of parsing numbers properly. Even if you have an older browser angular would take care of formatting them as numbers.
About problem 2:
Your answer is good Jason if you just need to show plain text on the screen. However if you would like to bind an input with a model to an arbitrary expression, you need something else.
I wrote a directive you can use to bind an ng-model to any expression you want. Whenever the expression changes the model is set to the new value.
module.directive('boundModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
scope.$watch(attrs.boundModel, function(newValue, oldValue) {
if(newValue != oldValue) {
ngModel.$setViewValue(newValue);
ngModel.$render();
}
});
}
};
})
You can use it in your templates like this:
<input type="text" ng-model="total" bound-model="value1 + value2">
Or like this:
<input type="text" ng-model="total" bound-model="cost()">
Where cost() is a simple function of the scope like this:
$scope.cost = function() { return $scope.val1 + $scope.val2 };
The good thing is that you keep using a model for your input and you don't have to dinamically update your value attribute, which doesn't work well in angular.
I'm new to AngularJS but I think that $parse could be used:
http://docs.angularjs.org/api/ng/service/$parse
This is interesting if you have the expression as a string. You can use a path of properties and that string can be generated dynamically. This works if you don't know the expression at compile time, a lot like eval() but probably a lot faster and maybe more secure(?).
Here's an example:
function Ctrl($scope,$parse) {
var expression = 'model.val1 + model.val2';//could be dynamically created
$scope.model = {
val1: 0,
val2: 0,
total: function() {
return ($parse(expression))($scope);
}
};
}
u can bind to a function
function CTRL ($scope) {
$scope.val1 = 3;
$scope.val2 = 4;
$scope.sum = function(){
return ($scope.val1 *1 + $scope.val2 *1);
};
}
it will work the same
the binding expression will work but in much more complex cases we need functions
The $watch function that is made available through the $scope variable is best for this job in my opinion.
$scope.$watch(function(scope) { return scope.data.myVar },
function(newValue, oldValue) {
document.getElementById("myElement").innerHTML =
"" + newValue + "";
}
);
The $watch function takes in a:
value function
& a listener function
The above example is taken from this awesome article: http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
After reading through it, I learnt a lot and was able to implement the solution I was looking for.

AngularJS : The correct way of binding to a service properties

I’m looking for the best practice of how to bind to a service property in AngularJS.
I have worked through multiple examples to understand how to bind to properties in a service that is created using AngularJS.
Below I have two examples of how to bind to properties in a service; they both work. The first example uses basic bindings and the second example used $scope.$watch to bind to the service properties
Are either of these example preferred when binding to properties in a service or is there another option that I’m not aware of that would be recommended?
The premise of these examples is that the service should updated its properties “lastUpdated” and “calls” every 5 seconds. Once the service properties are updated the view should reflect these changes. Both these example work successfully; I wonder if there is a better way of doing it.
Basic Binding
The following code can be view and ran here: http://plnkr.co/edit/d3c16z
<html>
<body ng-app="ServiceNotification" >
<div ng-controller="TimerCtrl1" style="border-style:dotted">
TimerCtrl1 <br/>
Last Updated: {{timerData.lastUpdated}}<br/>
Last Updated: {{timerData.calls}}<br/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script type="text/javascript">
var app = angular.module("ServiceNotification", []);
function TimerCtrl1($scope, Timer) {
$scope.timerData = Timer.data;
};
app.factory("Timer", function ($timeout) {
var data = { lastUpdated: new Date(), calls: 0 };
var updateTimer = function () {
data.lastUpdated = new Date();
data.calls += 1;
console.log("updateTimer: " + data.lastUpdated);
$timeout(updateTimer, 5000);
};
updateTimer();
return {
data: data
};
});
</script>
</body>
</html>
The other way I solved binding to service properties is to use $scope.$watch in the controller.
$scope.$watch
The following code can be view and ran here: http://plnkr.co/edit/dSBlC9
<html>
<body ng-app="ServiceNotification">
<div style="border-style:dotted" ng-controller="TimerCtrl1">
TimerCtrl1<br/>
Last Updated: {{lastUpdated}}<br/>
Last Updated: {{calls}}<br/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script type="text/javascript">
var app = angular.module("ServiceNotification", []);
function TimerCtrl1($scope, Timer) {
$scope.$watch(function () { return Timer.data.lastUpdated; },
function (value) {
console.log("In $watch - lastUpdated:" + value);
$scope.lastUpdated = value;
}
);
$scope.$watch(function () { return Timer.data.calls; },
function (value) {
console.log("In $watch - calls:" + value);
$scope.calls = value;
}
);
};
app.factory("Timer", function ($timeout) {
var data = { lastUpdated: new Date(), calls: 0 };
var updateTimer = function () {
data.lastUpdated = new Date();
data.calls += 1;
console.log("updateTimer: " + data.lastUpdated);
$timeout(updateTimer, 5000);
};
updateTimer();
return {
data: data
};
});
</script>
</body>
</html>
I’m aware that I can use $rootscope.$broadcast in the service and $root.$on in the controller, but in other examples that I’ve created that use $broadcast/$on the first broadcast is not captured by the controller, but additional calls that are broadcasted are triggered in the controller. If you are aware of a way to solve $rootscope.$broadcast problem, please provide an answer.
But to restate what I mentioned earlier, I would like to know the best practice of how to bind to a service properties.
Update
This question was originally asked and answered in April 2013. In May 2014, Gil Birman provided a new answer, which I changed as the correct answer. Since Gil Birman answer has very few up-votes, my concern is that people reading this question will disregard his answer in favor of other answers with many more votes. Before you make a decision on what's the best answer, I highly recommend Gil Birman's answer.
Consider some pros and cons of the second approach:
0 {{lastUpdated}} instead of {{timerData.lastUpdated}}, which could just as easily be {{timer.lastUpdated}}, which I might argue is more readable (but let's not argue... I'm giving this point a neutral rating so you decide for yourself)
+1 It may be convenient that the controller acts as a sort of API for the markup such that if somehow the structure of the data model changes you can (in theory) update the controller's API mappings without touching the html partial.
-1 However, theory isn't always practice and I usually find myself having to modify markup and controller logic when changes are called for, anyway. So the extra effort of writing the API negates it's advantage.
-1 Furthermore, this approach isn't very DRY.
-1 If you want to bind the data to ng-model your code become even less DRY as you have to re-package the $scope.scalar_values in the controller to make a new REST call.
-0.1 There's a tiny performance hit creating extra watcher(s). Also, if data properties are attached to the model that don't need to be watched in a particular controller they will create additional overhead for the deep watchers.
-1 What if multiple controllers need the same data models? That means that you have multiple API's to update with every model change.
$scope.timerData = Timer.data; is starting to sound mighty tempting right about now... Let's dive a little deeper into that last point... What kind of model changes were we talking about? A model on the back-end (server)? Or a model which is created and lives only in the front-end? In either case, what is essentially the data mapping API belongs in the front-end service layer, (an angular factory or service). (Note that your first example--my preference-- doesn't have such an API in the service layer, which is fine because it's simple enough it doesn't need it.)
In conclusion, everything does not have to be decoupled. And as far as decoupling the markup entirely from the data model, the drawbacks outweigh the advantages.
Controllers, in general shouldn't be littered with $scope = injectable.data.scalar's. Rather, they should be sprinkled with $scope = injectable.data's, promise.then(..)'s, and $scope.complexClickAction = function() {..}'s
As an alternative approach to achieve data-decoupling and thus view-encapsulation, the only place that it really makes sense to decouple the view from the model is with a directive. But even there, don't $watch scalar values in the controller or link functions. That won't save time or make the code any more maintainable nor readable. It won't even make testing easier since robust tests in angular usually test the resulting DOM anyway. Rather, in a directive demand your data API in object form, and favor using just the $watchers created by ng-bind.
Example
http://plnkr.co/edit/MVeU1GKRTN4bqA3h9Yio
<body ng-app="ServiceNotification">
<div style="border-style:dotted" ng-controller="TimerCtrl1">
TimerCtrl1<br/>
Bad:<br/>
Last Updated: {{lastUpdated}}<br/>
Last Updated: {{calls}}<br/>
Good:<br/>
Last Updated: {{data.lastUpdated}}<br/>
Last Updated: {{data.calls}}<br/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script type="text/javascript">
var app = angular.module("ServiceNotification", []);
function TimerCtrl1($scope, Timer) {
$scope.data = Timer.data;
$scope.lastUpdated = Timer.data.lastUpdated;
$scope.calls = Timer.data.calls;
};
app.factory("Timer", function ($timeout) {
var data = { lastUpdated: new Date(), calls: 0 };
var updateTimer = function () {
data.lastUpdated = new Date();
data.calls += 1;
console.log("updateTimer: " + data.lastUpdated);
$timeout(updateTimer, 500);
};
updateTimer();
return {
data: data
};
});
</script>
</body>
UPDATE: I've finally come back to this question to add that I don't think that either approach is "wrong". Originally I had written that Josh David Miller's answer was incorrect, but in retrospect his points are completely valid, especially his point about separation of concerns.
Separation of concerns aside (but tangentially related), there's another reason for defensive copying that I failed to consider. This question mostly deals with reading data directly from a service. But what if a developer on your team decides that the controller needs to transform the data in some trivial way before the view displays it? (Whether controllers should transform data at all is another discussion.) If she doesn't make a copy of the object first she might unwittingly cause regressions in another view component which consumes the same data.
What this question really highlights are architectural shortcomings of the typical angular application (and really any JavaScript application): tight coupling of concerns, and object mutability. I have recently become enamored with architecting application with React and immutable data structures. Doing so solves the following two problems wonderfully:
Separation of concerns: A component consumes all of it's data via props and has little-to-no reliance on global singletons (such as Angular services), and knows nothing about what happened above it in the view hierarchy.
Mutability: All props are immutable which eliminates the risk of unwitting data mutation.
Angular 2.0 is now on track to borrow heavily from React to achieve the two points above.
From my perspective, $watch would be the best practice way.
You can actually simplify your example a bit:
function TimerCtrl1($scope, Timer) {
$scope.$watch( function () { return Timer.data; }, function (data) {
$scope.lastUpdated = data.lastUpdated;
$scope.calls = data.calls;
}, true);
}
That's all you need.
Since the properties are updated simultaneously, you only need one watch. Also, since they come from a single, rather small object, I changed it to just watch the Timer.data property. The last parameter passed to $watch tells it to check for deep equality rather than just ensuring that the reference is the same.
To provide a little context, the reason I would prefer this method to placing the service value directly on the scope is to ensure proper separation of concerns. Your view shouldn't need to know anything about your services in order to operate. The job of the controller is to glue everything together; its job is to get the data from your services and process them in whatever way necessary and then to provide your view with whatever specifics it needs. But I don't think its job is to just pass the service right along to the view. Otherwise, what's the controller even doing there? The AngularJS developers followed the same reasoning when they chose not to include any "logic" in the templates (e.g. if statements).
To be fair, there are probably multiple perspectives here and I look forward to other answers.
Late to the party, but for future Googlers - don't use the provided answer.
JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".
In above example, instead of binding attributes of a service, why don't we expose the service to the scope?
$scope.hello = HelloService;
This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.
And if you are worried about your view accidentally overwriting your service attributes, use defineProperty to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.
Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.
In that particular demo code you supplied I would recommend you do:
function TimerCtrl1($scope, Timer) {
$scope.timer = Timer;
}
///Inside view
{{ timer.time_updated }}
{{ timer.other_property }}
etc...
Edit:
As I mentioned above, you can control the behaviour of your service attributes using defineProperty
Example:
// Lets expose a property named "propertyWithSetter" on our service
// and hook a setter function that automatically saves new value to db !
Object.defineProperty(self, 'propertyWithSetter', {
get: function() { return self.data.variable; },
set: function(newValue) {
self.data.variable = newValue;
// let's update the database too to reflect changes in data-model !
self.updateDatabaseWithNewData(data);
},
enumerable: true,
configurable: true
});
Now in our controller if we do
$scope.hello = HelloService;
$scope.hello.propertyWithSetter = 'NEW VALUE';
our service will change the value of propertyWithSetter and also post the new value to database somehow!
Or we can take any approach we want.
Refer to the MDN documentation for defineProperty.
I think this question has a contextual component.
If you're simply pulling data from a service & radiating that information to it's view, I think binding directly to the service property is just fine. I don't want to write a lot of boilerplate code to simply map service properties to model properties to consume in my view.
Further, performance in angular is based on two things. The first is how many bindings are on a page. The second is how expensive getter functions are. Misko talks about this here
If you need to perform instance specific logic on the service data (as opposed to data massaging applied within the service itself), and the outcome of this impacts the data model exposed to the view, then I would say a $watcher is appropriate, as long as the function isn't terribly expensive. In the case of an expensive function, I would suggest caching the results in a local (to controller) variable, performing your complex operations outside of the $watcher function, and then binding your scope to the result of that.
As a caveat, you shouldn't be hanging any properties directly off your $scope. The $scope variable is NOT your model. It has references to your model.
In my mind, "best practice" for simply radiating information from service down to view:
function TimerCtrl1($scope, Timer) {
$scope.model = {timerData: Timer.data};
};
And then your view would contain {{model.timerData.lastupdated}}.
Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.
In the example below changes to the Controller $scope.count variable will automatically be reflected in the Service count variable.
In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.
The code below can be seen working at http://jsfiddle.net/xuUHS/163/
View:
<div ng-controller="ServiceCtrl">
<p> This is my countService variable : {{count}}</p>
<input type="number" ng-model="count">
<p> This is my updated after click variable : {{countS}}</p>
<button ng-click="clickC()" >Controller ++ </button>
<button ng-click="chkC()" >Check Controller Count</button>
</br>
<button ng-click="clickS()" >Service ++ </button>
<button ng-click="chkS()" >Check Service Count</button>
</div>
Service/Controller:
var app = angular.module('myApp', []);
app.service('testService', function(){
var count = 10;
function incrementCount() {
count++;
return count;
};
function getCount() { return count; }
return {
get count() { return count },
set count(val) {
count = val;
},
getCount: getCount,
incrementCount: incrementCount
}
});
function ServiceCtrl($scope, testService)
{
Object.defineProperty($scope, 'count', {
get: function() { return testService.count; },
set: function(val) { testService.count = val; },
});
$scope.clickC = function () {
$scope.count++;
};
$scope.chkC = function () {
alert($scope.count);
};
$scope.clickS = function () {
++testService.count;
};
$scope.chkS = function () {
alert(testService.count);
};
}
I think it's a better way to bind on the service itself instead of the attributes on it.
Here's why:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<body ng-app="BindToService">
<div ng-controller="BindToServiceCtrl as ctrl">
ArrService.arrOne: <span ng-repeat="v in ArrService.arrOne">{{v}}</span>
<br />
ArrService.arrTwo: <span ng-repeat="v in ArrService.arrTwo">{{v}}</span>
<br />
<br />
<!-- This is empty since $scope.arrOne never changes -->
arrOne: <span ng-repeat="v in arrOne">{{v}}</span>
<br />
<!-- This is not empty since $scope.arrTwo === ArrService.arrTwo -->
<!-- Both of them point the memory space modified by the `push` function below -->
arrTwo: <span ng-repeat="v in arrTwo">{{v}}</span>
</div>
<script type="text/javascript">
var app = angular.module("BindToService", []);
app.controller("BindToServiceCtrl", function ($scope, ArrService) {
$scope.ArrService = ArrService;
$scope.arrOne = ArrService.arrOne;
$scope.arrTwo = ArrService.arrTwo;
});
app.service("ArrService", function ($interval) {
var that = this,
i = 0;
this.arrOne = [];
that.arrTwo = [];
$interval(function () {
// This will change arrOne (the pointer).
// However, $scope.arrOne is still same as the original arrOne.
that.arrOne = that.arrOne.concat([i]);
// This line changes the memory block pointed by arrTwo.
// And arrTwo (the pointer) itself never changes.
that.arrTwo.push(i);
i += 1;
}, 1000);
});
</script>
</body>
You can play it on this plunker.
I would rather keep my watchers a less as possible. My reason is based on my experiences and one might argue it theoretically.
The issue with using watchers is that you can use any property on scope to call any of the methods in any component or service you like.
In a real world project, pretty soon you'll end up with a non-tracable (better said hard to trace) chain of methods being called and values being changed which specially makes the on-boarding process tragic.
To bind any data,which sends service is not a good idea (architecture),but if you need it anymore I suggest you 2 ways to do that
1) you can get the data not inside you service.You can get data inside your controller/directive and you will not have a problem to bind it anywhere
2) you can use angularjs events.Whenever you want,you can send a signal(from $rootScope) and catch it wherever you want.You can even send a data on that eventName.
Maybe this can help you.
If you need more with examples,here is the link
http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html
What about
scope = _.extend(scope, ParentScope);
Where ParentScope is an injected service?
The Most Elegant Solutions...
app.service('svc', function(){ this.attr = []; return this; });
app.controller('ctrl', function($scope, svc){
$scope.attr = svc.attr || [];
$scope.$watch('attr', function(neo, old){ /* if necessary */ });
});
app.run(function($rootScope, svc){
$rootScope.svc = svc;
$rootScope.$watch('svc', function(neo, old){ /* change the world */ });
});
Also, I write EDAs (Event-Driven Architectures) so I tend to do something like the following [oversimplified version]:
var Service = function Service($rootScope) {
var $scope = $rootScope.$new(this);
$scope.that = [];
$scope.$watch('that', thatObserver, true);
function thatObserver(what) {
$scope.$broadcast('that:changed', what);
}
};
Then, I put a listener in my controller on the desired channel and just keep my local scope up to date this way.
In conclusion, there's not much of a "Best Practice" -- rather, its mostly preference -- as long as you're keeping things SOLID and employing weak coupling. The reason I would advocate the latter code is because EDAs have the lowest coupling feasible by nature. And if you aren't too concerned about this fact, let us avoid working on the same project together.
Hope this helps...

Resources