Access config constants inside view in angularjs - angularjs

I've configured a constant on a module like below(simplified version of my actual scenario):
var app = angular.module('app', []);
angular.config('AnalyticsConstant', function(){
property: {
click: 'clicked',
swipe: 'swiped',
externalLink: 'opened external link'
},
page: {
message: {
list: 'Message listing',
show: 'Message show'
}
}
}
Now I based on user action taken (say swipe), I want to trigger an analytics event. Since swipe/click or recognizing if an element has an external link, is something done on view level, I want to pass a hash to my controller method.
for example:
<ion-list>
<ion-item ng-repeat="message in messages track by $index" ui-sref="message_path({id: message.id})" class="item-text-wrap">
<my-track-directive source='message', property='click'>
</ion-item>
</ion-list>
Here certainly in myTrackDirective, I can read these two values and check if source/property key is available in AnalyticsConstant. Once found out, I'll also have to check if the value are key another key in AnalyticsConstant.source/property hash. Another pain will be, I'll need to stringify the keys source/property so that I can check in hash, however that's not a problem.
I was wondering if I can access the AnalyticsConstant in view, so that the directive line becomes something like:
<my-track-directive source='AnalyticsConstant[page][message][list]', userAction='AnalyticsConstant[property][click]'>
I could think of three solutions:
Add inject it root scope. ie.
app.run(function($rootScope, AnalyticsConstant){
$rootScope.analyticsConstant = AnalyticsConstant
}
But this is not a good solution, as if by mistake anyone changes $rootScope.analyticsConstant to something else, whole functionality may get screwed.
Inject in each controller and set it at $scope level.
$scope.analyticsConstant = AnalyticsConstant
This will be a lot of duplication. Also, it'll also not ensure if $scope.analyticsConstant won't get corrupted by mistake.(Though disaster will also be scoped and limited :) )
Write a function which returns AnalyticsConstant inside 'module.run' or may be inside each controller.
function getAnalyticsConstant = function(){
return AnalyticsConstant
}
I particularly liked the third approach. But question remains where to place this (rootScope or controller-scope)?
My questions are:
Is there any better way to access configured constant inside view in angular?
What might be other problems with each of these approach I listed above?
Is the directive approach is better or should I collect this data in some model and then pass it to analytics event function ?
Thanks

I would use value to define constants:
app.value('AnalyticsConstant', function(){
property: {
click: 'clicked',
swipe: 'swiped',
externalLink: 'opened external link'
},
page: {
message: {
list: 'Message listing',
show: 'Message show'
}
}
}
So in each controller/directive you just nee to create instance, for example:
app.directive('myTrackDirective', ['AnalyticsConstant', function(AnalyticsConstant) {
return {
restrict: 'E',
replace: true,
scope: {/* ... */},
templateUrl: 'some.html',
link: function(scope) {
scope.AnalyticsConstant = AnalyticsConstant;
}
};
}]);
After you can call AnalyticsConstant from HTML
As a side note (doesn't refer to question):
Try to use MixPanel. Works great for Cordova-Ionic-Angular

Related

angular array item not updating on scope change

Spent a few hours on this already, sifted through numerous stack posts and blogs but can't seem to get this to make my model update. More specifically, I am trying to update an array item (ng-repeat). In the simple case below, I iterate over venues list, and upon toggling a "like" button, I update the server appropriately, and reflect the change on the venues item on the $scope.
in my search.html I have a directive:
<ion-content>
<venues-list venues="venues"></venues-list>
</ion-content>
and search controller I have:
app.controller('bleh', function(Service) {
...
$scope.venues = [{ id: 1, name: 'Venue1', like: false },{ id: 2, name: 'Venue2', like: false }];
...
});
Nothing unusual there. Then in my venues-list directive:
app.directive('venues-list', function() {
function venueListController($scope, Service) {
$scope.likeToggle = function(venue, $index) {
Service.likeVenue(venue.id, !venue.like).then(function() {
$scope.venues[$index].like= !venue.like;
});
}
}
return {
strict: 'E',
templateUrl: 'venue.html',
controller: venueListController,
scope: {
venues: '='
}
}
});
then in my venue.html I have:
<div ng-repeat="venue in venues">
<p>{{venue.name}}</p>
<button ng-click="likeToggle(venue, $index)">Like</button>
</div>
I have tried many different options:
$scope.$apply() // after updating the $scope or updating scope within apply's callback function;
$scope.$digest()
$timeout(function() { // $scope.venues[$index] .... }, 0);
safe(s,f){(s.$$phase||s.$root.$$phase)?f():s.$apply(f);}
so
safe($scope, function() { $scope.venues[$index].like = !venue.like });
I haven't yet used the link within the directive, but my venues.html template is obviously a little more elaborate than presented here.
EDIT:
Just to keep the discussion relevant, perhaps I should have mentioned - the data is coming back from the server with no issues, I am handling errors and I am definitely hitting the portion of the code where the $scope is to be updated. NOTE: the above code is a small representation of the full app, but all the fundamental pieces are articulated above.
Search Controller
Venues Service
venue-list directive and venue.html template to accompany the directive
directive controller
EDIT #2
$scope.foo = function() {
$scope.venues[0].like = !$scope.venues[0].like;
}
Just to keep it even simpler, the above doesn't work - so really, the bottom line is my items within an array are not reflecting the updates ...
EDIT #3
$scope.foo = function() {
$scope.venues[0].like = !$scope.venues[0].like;
}
My apologies - just to re-iterate what I was trying to say above - the above is changing the scope, however, the changes are not being reflected on the view.
Perhaps the issue is with your service and promise resolution.. Can you put a console.log there and see if the promise resolution is working fine? or Can you share that code bit. Also where are you checking for scope update? within directive or outside
OK after some refactoring I finally got it working.
The "fix" (if you want to call it that) to my specific problem was:
instead of passing an array of venues, I was iterating over the array on the parent controller, passing in a venue as an element attribute that would bind (two-way) on the isolated scope of the directive.
so, instead of:
<ion-content>
<venues-list venues="venues"></venues-list>
</ion-content>
I now have:
<ion-content>
<venues-list ng-repeat="venue in venues" venue="venue"></venues-list>
</ion-content>
and my directive now looks like:
app.directive('venues-list', function() {
function venueController($scope, Service) {
$scope.likeToggle = function(venue) {
Service.likeVenue(venue.id, !venue.like).then(function() {
$scope.venue.like = !venue.like;
});
}
}
return {
strict: 'E',
templateUrl: 'venue.html',
controller: venueController,
scope: {
venue: '='
}
}
});
This did the trick!

Angular directive from array element in ngRepeat

I am working on a project that will have any number of HTML cards, and the format and positioning of the cards is the same, but the content of them will differ.
My plan was to implement the content of each card as an angular directive, and then using ngRepeat, loop through my array of directives which can be in any order, displaying each directive in a card. It would be something like this:
inside my controller:
$scope.cards = [
'directice-one',
'directive-two',
//etc..
]
my directive:
.directive('directiveOne', function () {
return {
restrict: "C",
template: '<h1>One!!</h1>'
};
})
.directive('directiveTwo', function () {
return {
restrict: "C",
template: '<h1>Two!!</h1>'
};
})
//etc..
my html:
<div class="card" ng-repeat="item in cards">
<div class="{{item}}"></div>
</div>
But.. the directives don't render. So I just get a div with class="directive-one".
This might be a design flaw on my part, some sort of syntax error, or just a limitation of angular. I'm not sure.
I've also considered making a directive <card>, and then passing the templateUrl: into it, but that would cause me to lose my access to $scope and the javsacript capabilities that I would have if each card was it's own directive.
So, advise, code help, anything would be very helpful!
I choose directives only when I need to use them in HTML mark up. For example, assuming cards layout is same and it takes different information based on user preference.
HTML File
<my-card Name="First" Option="Myoptions"></Card>
<my-card Name="Second" Option="GenOptions"></Card>
Directive
angular.module("testapp").directive("MyCard", function() {
scope: {
name: '#',
Option: '#'
Controller: "myCardController",
templateURL: "~/myCard/myCardTemplate.html"
}
});
In Template you can implement the information passed from HTML page via the directive.
Hope this helps.
Do take note that the above approach is preferred when you are developing a framework sort of things. For example you develop a web framework and the header takes 5 parameters and these 5 parameters needs to be passed via mark up. Most important thing is that the framework/header is independent
In your controller, you need to require the directive modules. Then assign them to a scope variable which would be that array you have. Will update with code when I get to desktop, tried doing with phone kinda tuff.

AngularJS setting model value from directive and calling a parent scope function holds on to the previous value inside that function

js fiddle http://jsfiddle.net/suras/JzaV9/4/
This is my directive
'use strict';
barterApp.directive('autosuggest', function($timeout, $http) {
return {
restrict: "E",
scope: {
modelupdate:"=",
suggestions:"=",
urlsend:"#"
},
template: '<ul><li ng-repeat="suggest in suggestions" ng-click="updateModel(suggest)">{{suggest}}</li></ul>',
link: function (scope, element) {
scope.$watch('modelupdate', function() {
$timeout(function(){
$http.post(scope.urlsend, {q:scope.modelupdate}).then(function(data){
scope.suggestions = data.data;
console.log(data.data);
});
}, 3000);
});
scope.updateModel = function(value){
scope.modelupdate = value;
scope.$parent.getBookInfo();
}
}
};
});
controller is
barterApp.controller('openLibraryCtrl', ['$scope','$http',function ($scope,$http) {
$scope.title = "";
$scope.getBookInfo = function(value){
if($scope.title == "" || $scope.title == " ") //here title is 'r'(previous value)
{
return;
}
$http.get('/book_info.json?q='+$scope.title).then(function(res){
if(Object.keys(res).length !== 0)
{
data = res.data
console.log(data);
}
});
}
//here title is 'rails' (updated value from directive).
//( used a watch function here on model update
// and checked it but inside getBookInfo it is still 'r' )
}]);
in the update model function i set the model value and call the getBookInfo function on parent scope. but the thing here is when (this is a autocomplete) i enter the value in a input field that contains ng-model say for example 'r' then triggers the watch and i get suggestions from a post url (lets say "rails", "rock") and show it through the template as in the directive. when i click one of the suggestions (say 'rails') it triggers the updatemodel function in directive and sets the model value. its fine upto this but when i call the getBookInfo function in parent scope then $scope.title is 'r' inside the function (i checked with console log outside the function the model value was updated correctly as 'rails' ). again when i click 'rock' the model value inside getBookInfo is 'rails'.
i have no clue whats going on. (i also tested with watch function in controller the model gets updated correctly but the function call to getBookInfo holds back to the previous value)
view
<form ng-controller="openLibraryController">
<input type="text" ng-model="title" id="title" name="book[title]" />
<autosuggest modelupdate = "title" suggestions = "book_suggestions" urlsend="/book_suggestions.json"> </autosuggest>
</form>
I didn't look deep into it, but I suspect (with a high degree of confidence) that the parent scope has not been updated at the time of calling getBookInfo() (since we are still in the middle of a $digest cycle).
Not-so-good Solution 1:
You could immediately update the parent scope as well (e.g. scope.$parent.title = ...), but this is clearly a bad idea (for the same reasons as nr 2, but even more so).
Not-so-good Solution 2:
You could pass the new title as a parameter to getBookInfo().
Both solutions result in mixing controller code with directive code and creating a tight coupling between your components, which as a result become less reusable and less testable.
Not-so-bad Solution:
You could watch over the title and call getBookInfo() whenever it changes:
$scope.$watch('title', function (newValue, oldValue) {
getBookInfo();
});
This would be fine, except for the fact that it is totally unnecessary.
Better Solution:
Angular is supposed to take care of all that keep-in-sync stuff for us and it actually does. You don't have given much context on what is the purpose of calling getBookInfo(), but I am guessing you intend to update the view with some info on the selected book.
In that case you could just bind it to an element (using ng-bind) and Angular will make sure it is executed properly and timely.
E.g.:
<div>Book info: <span ng-bind="getBookInfo()"></span></div>
Further more, the autosuggest directive doesn't have to know anything about it. It should only care about displaying suggestions, manipulating the DOM (if necessary) and updating the specified model property (e.g. title) whenever a suggestion is clicked. What you do with the updated value should be none of its business.
(BTW, ideally the suggestions should be provided by a service.)
Below is a modified example (based on your code) that solves the problem. As stated above there are several methods of solving the problem, I just feel this one tobe cleaner and more aligned to the "Angular way":
Book title: <input type="text" ng-model="book.title" />
<autosuggest modelupdate="book.title"
suggestions="book.suggest()"></autosuggest>
Book info: <span ng-bind="book.getInfo()"></span>
Just by looking at the HTML (without knowing what is in JS), one can easily tell what is going on:
There is a text-field bound to book.title.
There is a custom autosuggest thingy that offers suggestions provided by book.suggest() and updates book.title.
There is a span that displays info about the book.
The corresponding directive looks like this:
app.directive('autosuggest', function() {
return {
restrict: 'E',
scope: {
modelupdate: '=',
suggestions: '&'
},
template:
'<ul><li ng-repeat="suggest in suggestions()" ' +
'ng-click="modelupdated = suggest">' +
'{{suggest}}</li></ul>'
};
});
As you can see, all the directive knows about is how to retrieve suggestions and what to update.
Note that the same directive can be used with any type of "suggestables" (even ones that don't have getBookInfo()); just pass in the right attributes (modelupdated, suggestions).
Note also, that we could remove the autosuggest element and the app would continue to work as expected (no suggestions of cource) without any further modification in HTML or JS (while in your version the book info would have stopped updating).
You can find the full version of this short demo here.

Understanding the 'directive' paradigm in Angularjs

I have been thinking about directives in Angularjs like user controls in ASP.Net, and perhaps I have it wrong.
A user control lets you encapsulate a bunch of functionality into a widget that can be dropped into any page anywhere. The parent page doesn't have to provide anything to the widget. I am having trouble getting directives to do anything close to that. Suppose that I have an app where, once the user has logged in I hang onto the first/last name of the user in a global variable somewhere. Now, I want to create a directive called 'loggedinuser' and drop it into any page I want. It will render a simple div with the name of the logged in user pulled from that global variable. How do I do that without having to have the controller pass that information into the directive? I want the usage of the directive in my view to look as simple as
<loggedinuser/>
Is this possible?
I guess you can roughly sum up what a directive is as "something that encapsulates a bunch of functionality into a widget that can be dropped into any page anywhere", but there's more to it than that. A directive is a way to extend HTML by creating new tags, allowing you to write more expressive markup. For instance, instead of writing a <div> and a bunch of <li> tags in order to create a rating control, you could wrap it up with a new <rating> tag. Or, instead of lots of <div>s, and <span>s and whatnot to create a tabbed interface, you could implement a pair of directives, say, <tab> and <tab-page>, and use them like this:
<tab>
<tab-page title="Tab 1"> tab content goes here </tab-page>
<tab-page title="Tab 2"> tab content goes here </tab-page>
</tab>
That's the truly power of directives, to enhance HTML. And that doesn't mean that you should only create "generic" directives; you can and should make components specific to your application. So, back to your question, you could implement a <loggedinuser> tag to display the name of the logged user without requiring a controller to provide it with the information. But you definitely shouldn't rely on a global variable for that. The Angular way to do it would be make use of a service to store that information, and inject it into the directive:
app.controller('MainCtrl', function($scope, userInfo) {
$scope.logIn = function() {
userInfo.logIn('Walter White');
};
$scope.logOut = function() {
userInfo.logOut();
};
});
app.service('userInfo', function() {
this.username = ''
this.logIn = function(username) {
this.username = username;
};
this.logOut = function() {
this.username = '';
};
});
app.directive('loggedinUser', function(userInfo) {
return {
restrict: 'E',
scope: true,
template: '<h1>{{ userInfo.username }}</h1>',
controller: function($scope) {
$scope.userInfo = userInfo;
}
};
});
Plunker here.
The Angular dev guide on directives is a must-go place if you want to start creating powerful, reusable directives.

Angularjs menu login logout loading

I am using Angularjs in a project.
For login logout I am setting a scope variable like below:
$scope.showButton = MyAuthService.isAuthenticated();
In markup its like
<li ng-show="showLogout">Logout</li>
When I logout it redirect to the login page but logout menu doesn't disappear.
Also tried like this:
$scope.showButton = MyAuthService.isAuthenticated();
In markup:
<li ng-class=" showLogout ? 'showLogout' : 'hideLogOut' ">Logout</li>
Seems scope change is not reflecting in my view, but when I reload page "logout menu" disappears as expected.
I also tried with directives like below:
MyApp.directive('logoutbutton', function(MyAuthService) {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
attrs.$observe('logoutbutton', function() {
updateCSS();
});
function updateCSS() {
if (MyAuthService.isAuthorized()) {
element.css('display', 'inline');
} else {
element.css('display', 'none');
}
}
}
}
});
No luck with that too.
How can I hide it when the logout is successful and also after successful login how can I show "logout button"?
Setup a watch on MyAuthService.isAuthenticated() and when that fires, set your scope variable to the result of that service call. In your first example, the scope variable is only getting set once when the controller is initialized (I am assuming that's where it is being run). You can set the watch up in the controller or, if you want to use a directive, in the directive link function.
Something like this:
$scope.$watch(MyAuthService.isAuthenticated, function(newVal, oldVal){
$scope.showButton = newVal;
});
Edit: After read the MarkRajcok comment I realized that this solution is coupling view from business logic layer, also it exposes the service variable to be changed outside the service logic, this is undesirable and error prone, so the $scope.$watch solution proposed by BoxerBucks it's probably better, sorry.
You can use $scope.$watch as in the BoxerBucks answer, but I think that using watchers isn't proper for services, because usually you want to access services variables in differents controllers expecting that when you change that services variables, all the controllers that inject that service will be automatically updated, so I believe that this is a good way to solve your problem:
In your MyAuthServices do this:
app.service('MyAuthService', function(...){
var MyAuthServiceObj = this;
this.authenticated=false; // this is a boolean that will be modified by the following methods:
// I supose that you have methods similar to these ones
this.authenticateUser(...){
...
// At some point you set the authenticated var to true
MyAuthServiceObj.authenticated = true;
}
this.logout(){
....
// At some point you set the authenticated var to false
MyAuthServiceObj.authenticated = false;
}
});
Then in your controller do this:
$scope.myAuthService = MyAuthService;
finally in your html:
ng-show="myAuthService.authenticated"
And this should work without using a watcher like in BoxerBucks answer.
Check this excellent video about AngularJS providers, to understand how to use services properly.

Resources