Should AngularJS logic be placed in HTML file? - javascript

I want to refactor code of which I post examples below. I am very new to AngularJS. Now when I saw the code, I was very curious about all the logic that is placed in the HTML code.
<p ng-show="countForm.count.$dirty && countForm.count.$error.min" class="error-message">
<button ng-click="step(2)" ng-show="data.step == 1 && countForm.count.$dirty" ng-disabled="countForm.$invalid" class="line-break">
<div ng-class="{selected: data.spreadChoice == 3}" ng-click="data.spreadChoice = 3; step(3)" ng-mouseover="data.preSpreadChoice = 3" ng-mouseout="data.preSpreadChoice = data.spreadChoice">
<div ng-show="data.step >= 2" class="step" ng-class="{active: data.step == 3, done: data.step > 3, left: data.preSpreadChoice == 1, right: data.preSpreadChoice == 3}" ng-scroll-here="data.step == 3">
<p ng-switch-when="false" class="large">[[data.emails.length]] von [[data.count]] – <span class="red">[[Math.max(0,data.count-data.emails.length)]]</span> Members</p>
<div ng-show="data.step >= 5 && data.multipleTeams" class="step" ng-class="{done: data.step > 5, active: data.step == 5}" ng-scroll-here="data.step == 5">
<button class="small" ng-disabled="!unitsForm.$dirty || unitsForm.$invalid" ng-click="addUnit(data.nextTeam, data.nextTeamleaderEmail)">
Shouldn't the HTML rather contain classes or attributes and the logic itself should be placed in JS files or JS code? Is this a good (or at least a common) way of developing AngularJS? Or should placing logic in HTML be avoided?

If you ask me:
Client side business logic sits in services that are injected into directives\controllers.
UI logic is suppose to be placed in the controllers.
Now about adding logic to the views, if we are talking about business logic then it's a big no no. Use a method on your controller that will evaluate stuff using the service.
If we are talking about ng-if/ng-show conditions then only if they are small and "readable" conditions I would add them to the view. When it's more than that, I move them to the controller for debugging issues and since I believe the HTML should be readable.

Placing logic in HTML using directives in angular is a good way. You cannot take full advantage of angular without placing logic in HTML.
Controllers should contain view logic, but shouldn’t actually reference the DOM (referencing the DOM should only be done through directives). ref
Two things to remember or the best practices for AngularJS are
Treat the scope as read-only in views
Treat the scope as write-only in controllers
ref
Since you are placing logic in HTML, if you treat it as read-only, you can check conditions or extract data using functions in scope, but the original data model isn't disturbed whatever you do in HTML.
Also tying dom elements to specific directives are the most powerful features of angular.
When you use a datepicker, in jQuery, you could do as follows:
<div id="datepicker"></div>
then in JS:
jQuery('#datepicker').datepicker({
start:'today',
end:'tomorrow',
showTime:true
})
You can do this in angular way as follows
This way even when a designer or someone who reads HTML will be able to read what and even you can pass the options from the element's attributes itself.
<div date-picker start="today" end="tomorrow" show-time="true"></div>
AngularJS's importance itself is declarative syntax and can contain expressions as attribute values like you posted. That is not at all a bad practice. Indeed it is common and good practice all developers do. Using logic in HTML in angularjs saves a lot of code writing by ourselves. All the heavylifting is done by angular behind the scenes.
See some best practices about AngularJS

Related

Which element does myVar bind to? Problems with `ng-init` [duplicate]

This question already has answers here:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
(3 answers)
Closed 5 years ago.
I'm wondering what's happening behind the scenes when using ng-init.
Sometimes ng-init does some unexpected things, and I have a hard time debugging.
Let's say I have the following structure:
<!-- App -->
<div ui-view>
<!-- Component -->
<custom-component>
<!-- Transcluded component -->
<transcluded-component>
<!-- Controller -->
<div ng-controller="MyCtrl">
<!-- Element -->
<div ng-init="myVar = 'hello'">
{{myVar}}
</div>
</div>
</transcluded-component>
</custom-component>
</div>
Which element does myVar bind to?
Edit 2017-07-21: Added an example
In the following template block (especially within an ng-repeat), I may use an ng-init:
<span ng-init="path = getPath()">
<a ng-if="path" ng-href="path">
Click here
</a>
<span ng-if="!path">
Some text
</span>
</span>
In this case, I skipped a function call twice, and kept my template clean.
Sometimes ng-init does some unexpected things, and I have a hard time debugging.
The ng-init directive evaluates an Angular Expression in the context of the scope of its element. Numerous directives (ng-repeat, ng-controller, ng-if, ng-view, etc.) create their own scope.
For more information, see
AngularJS Developer Reference - scopes
AngularJS Wiki - Nuances of Scope Prototypical Inheritance
Avoid using ng-init
Avoid using ng-init. It tangles the Model and View, making code difficult to understand, debug and maintain. Instead initialize the Model in the controller.
From the Docs:
ngInit
This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.
— AngularJS ng-init Directive API Reference
Update
Q: I've also added an example of a code block I sometime use.
<!-- Controller -->
<div ng-controller="MyCtrl">
<!-- Element -->
<div ng-init="myVar = 'hello'">
{{myVar}}
</div>
</div>
To do the equivalent initialization in the controller:
app.controller("MyVar", function($scope) {
this.$onInit = function() {
$scope.myVar = 'hello';
};
});
By separating concerns of Model and View, the code becomes easier to understand, debug and maintain.

How does childscope work on an ng-if statement? Specifically in a <SELECT> element

NOTE: I'm a new member here so I couldn't directly comment and ask for clarification.
So, my question is: How can I work around ng-if creating a child scope for a select element?
I have the following code:
HTML
<select id="project-select"
ng-if="projects.length > 0"
ng-options="project.name for project in projects"
ng-model="currentProject"
ng-change="broadcastChange('project-changed', currentProject)">
</select>
And my controller is set up in the following format:
function Controller() {
//Do code stuffz
}
angular
.module('app')
.controller('Controller', Controller);
I learned from this post that the "ng-if" is creating a child scope.
So even when the model changes, this part stays the same because it is a primitive value: (name is just a string)
<div id="current-project" class="pull-left">
<strong>Project: </strong>{{currentProject.name}}
</div>
Furthermore in the aforementioned post there were a couple options.
a. Simply change to this: ng-model="$parent.currentProject" which feels a little hacky
b. Set the object value in the controller, which I'm not entirely sure how to do. I feel like it's an easy fix, but I'm somehow overcomplicating it.
Anyway, for now I simply changed ng-if to ng-show and that's solved the problem. However, I am trying to understand Angular more deeply and I feel like this issue could be explained a little bit better to me. Thanks in advance!
What you will find with Angular scope variables is: always use a dot.
That's the mantra from the excellent ng-book
In your case, what this means is this:
You have this code:
<select id="project-select"
ng-if="projects.length > 0"
ng-options="project.name for project in projects"
ng-model="currentProject"
ng-change="broadcastChange('project-changed', currentProject)">
</select>
Which means that you are binding to a $scope variable called $scope.currentProject.
Because of the mysterious and awesome way that javascript works, this does not get updated when you are inside of a child scope.
Thankfully, the solution is actually quite simple. Instead, create an object like so:
$scope.myData = {
currentProject: ''
}
And in your markup, bind to that like so:
<select id="project-select"
ng-if="projects.length > 0"
ng-options="project.name for project in projects"
ng-model="myData.currentProject"
ng-change="broadcastChange('project-changed', myData.currentProject)">
</select>
And voila. It will update, even though it's in a child scope.
This is actually quite useful, because you now have a way to "meaningfully" group variables together. Here's some other pseudo-code to demonstrate what I mean:
$scope.projectData = {
currentProjectID: 1,
currentProjectTitle: 'My Cool Project',
projects: [
{id: 1, name: 'My Cool Project'},
{id: 2, name: 'Another Project'}
],
someOtherProperty: false
// ...etc....
}
As a side-note, this section of this article might be helpful: http://docstore.mik.ua/orelly/webprog/jscript/ch11_02.htm#jscript4-CHP-11-SECT-2.1
If all you want to do is show/hide the select element based on the projects in your 'Controller' controller scope, then ng-show is the right way to go here. In my experience, I've used ng-if when I'm conditionally loading a larger "partial" view containing numerous controls where I felt a separate scope was necessary to avoid having a very large scope (or to facilitate re-use).
You are correct. Do not use $parent in any production Angular apps. It makes your model dependent on the structure of your view, which makes your code hard to refactor and less modularized.
Binding to object properties is the way to go, as you suggested in your "b" answer. The recommended way to do this in the latest version of Angular 1.x is by using the "controller as" syntax. This method makes use of "prototypical inheritance" in javascript. There is a good explanation on this here: http://javascript.info/tutorial/inheritance
I created a plunker for you to demonstrate how binding to object properties works in nested scopes. take a look at the "controller as" syntax". also, try changing the value of ctrl.testBinding in the input, you will see that reflected in the ng-if child scope. I will try to find some links to explain this in more detail.
https://plnkr.co/edit/Gx5xbkJXgzjPSG8kajPR?p=preview
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl as ctrl">
<input ng-model="ctrl.testBinding" type="text"/>
<button ng-click="ctrl.toggle()">toggle show</button>
<div ng-if="ctrl.show">
{{ ctrl.testBinding }}
</div>
</div>
</body>
</html>
//script.js
function testController($scope) {
var vm = this;
vm.show = true;
vm.toggle = function(){
vm.show = !vm.show
}
}
angular
.module('testApp', [])
.controller('testCtrl', testController);

angularjs dynamically change footer

In my app for android I have multiple html's, most of them have the same footer with three icons, but some of the pages have different footers with 2 or 3 icons.
What is the correct way to accomplish this?
Because I would like to maintain mu ion-footer-bar in the main.html with the ion-header-bar, ion-nav-bar and ion-nav-view(where are showed all htmls).
I've tried to use a sort of ng-repeat with conditional reading of a structure depending on the current page, also using a tabs.html with different sections with different id's, none of the two solutions is working and I messed to much the code, so while I continue trying I would like to know if one of these approximations is correct.
thanks
You could use ng-show and ng-include to conditionally load in the right template from a set of footer html templates.
<div ng-show="$scope.template == 'footer_one'" >
<div ng-include src="'/partials/footer_one.html'"></div>
</div>
<div ng-show="$scope.template == 'footer_two'" >
<div ng-include src="'/partials/footer_two.html'"></div>
</div>
You'd need to programmatically set the $scope.template variable based on some condition in the controller.

AngularJS - Run directives explicitly

I'm new to AngularJS and I'm struggling with the following issue.
I need to implement a 3 step workflow as follows:
Make a call to a web service that returns a list of strings. For example, ["apple", "banana", "orange"], etc. I intercept the response and add the angle brackets around each of these strings before I send it to the Views.
For each of the string returned by the service, I have to render
<apple />
<banana />
<orange />
Finally, get the actual AngularJS directive corresponding to each of those strings to "execute" (not sure what the right word is) and replace the elements above with the content from the templateUrl property as mentioned in each of their respective directives.
Right now, I'm doing Step 1 and Step 2 above using AngularJS. But I understand that they can be done using plain JavaScript using AJAX calls.
My problem is that the directives don't get "run" or "executed" and I have these tags displayed as plain text on the page -
<apple />
<banana />
<orange />
etc.
How do I tell Angular to replace the custom tags with the actual content from their templates?
Thanks for your help.
UPDATE: Here's what the code looks like:
<div class="content" ng-controller="mainController">
<ul class="feeds">
<li ng-repeat="fruit in fruits">
<div ng-controller="fruitSpecificController"> {{fruit}} </div> <!-- This renders <apple />, <banana />, etc. -->
</li>
</ul>
</div>
Also note that each fruit can have its own controller. In the code above, I say "fruitSpecificController", but ideally that would also be generated at runtime. For example, "appleController", "orangeController", etc. and yes, they'll be child controllers of the parent "mainController".
You can use the compile method, but there is a built in directive that will do this for you - if you are willing to load in via a URL.
ng-include
Using ng-include="'/path/to/template.html'" - the evaluated expression URL will be requested and added to the DOM as a child (compiled for you).
You can also cache the templates using $templateCache (if you want to request multiple templates at the same time or cache it for multiple includes).
That would look something like this:
$templateCache.put(/path/to/template.html, 'apple html string');
custom directive (with $compile)
Otherwise, if you want to load in and compile a string - use a directive inside of a ng-repeat.
.directive('unsafeHtmlCompile', function($compile){
return {
link: function(scope, element, attrs){
scope.$watch(attrs.unsafeHtmlCompile, function(val){
if(val !== undefined){
element.html('');
var el = angular.element(val);
element.append(html);
$compile(el)(scope);
}
});
}
}
}
Remember to remove the watcher, if your data won't change :-)
You probably just need to use the $compile service. The docs aren't super helpful but the gist is that you call $compile, passing in the DOM element (in your case the parent of your directives). That returns a function that you then execute, passing in the scope that you want to use ($rootscope is probably safe).
$compile(element)($rootScope);

ExpressionEngine putting Javascript on a page

I am a super beginner to EE and was literally thrust into managing my company's website that is built in EE without training. I'm not a programmer, I'm a designer, so it's been taking me awhile to plug through this. So I might need some dumbed down language :)
I want to create a page that has some Javascript on it. Do I need to create a new template JUST so I can put some javascript on it? And how do I communicate to EE that I want the page I created to go with that template?
I duplicated the page/index template and renamed it to clinician-map (the same name of the page I created in the publisher). EE didn't like that and the page subsequently broke. All I want to do is insert one javascript item, this seems way too inefficient for just one page. Help??
(using EE 1.6.8)
Here is my code from clinician-map template.
{assign_variable:my_weblog="page"}
{assign_variable:my_template_group="page"}
{embed="embeds/html_head" url_title="{segment_2}"}
{embed="embeds/html_styles"}
{embed="embeds/html_scripts"}
<?php include_once("analyticstracking.php") ?>
</head>
{exp:weblog:entries weblog="{my_weblog}" disable="categories|member_data|pagination|trackbacks" limit="1" sort="asc" }
<body class="{url_title}">
{/exp:weblog:entries}
<div id="wrapper">
{embed="embeds/html_headerPlusLeftNav"}
<div id="content">
<div id="contentMain">
{exp:weblog:entries weblog="{my_weblog}" disable="categories|member_data|pagination|trackbacks" limit="1" sort="asc"}
<h2>{title}</h2>
{page_body}
{/exp:weblog:entries}
<!--contactforminfo -->
{exp:weblog:entries weblog="{my_weblog}" disable="categories|member_data|pagination|trackbacks"}
{related_entries id="playa_contentcalloutitems"}
<div class="callout">
<h3>{title}</h3>
{callout_summary}
</div>
{/related_entries}
{/exp:weblog:entries}
{exp:weblog:entries weblog="{my_weblog}" disable="categories|member_data|pagination|trackbacks"}
{related_entries id="playa_contentfeatureditems"}
<div class="featuredContent">
<h3>{title}</h3>
{exp:word_limit total="50"}
{contentfeatured_summary}
{/exp:word_limit}{if contentfeatured_body!=""}<p><a href='{url_title_path='content-featured/'}' class='more'>Read More</a></p>{/if}
</div>
{/related_entries}
{/exp:weblog:entries}
</div>
{exp:weblog:entries weblog="{my_weblog}" disable="categories|member_data|pagination|trackbacks"}
<div id="contentSub">{related_entries id="playa_contentsubitems"}<div class="item {contentsub_bgcolor}">
{if contentsub_contenttype=="Text or Picture with Text"}
<h3>{title}</h3>
{exp:word_limit total="50"}
{contentsub_summary}
{/exp:word_limit}{if contentsub_body!=""}<p><a href='{url_title_path='content-sub/'}' class='more'>Read More</a></p>{/if}
{if:else}
<h3 class="imgHeader">{title}</h3>
{exp:html_strip convert="y" convert_back="none" keep="a,img"}
{contentsub_summary}
{/exp:html_strip}
{/if}
</div>{/related_entries}
{/exp:weblog:entries}
{embed="embeds/html_mailingListSignup"}
</div>
</div>
{embed="embeds/html_footer"}
</div>
</body>
</html>
At glance I can see a couple things that might be confounding you...
You started with a template called 'index' in the 'page' template group.
Looks like the 'page' template you are starting from is meant to display a single entry from the 'page' weblog.
So a request url might look something like this:
http://example.com/page/some_url_title
where 'some_url_title' is the 'url_title' value one of the entries in your 'page' weblog.
Now you have gone and duplicated the index template and called this new template 'clinician-map'.
So you would call an entry through this template at:
http://example.com/page/clinician-map/some_url_title
Now, notice that the first url had 2 segments, while the second had 3 segments?
That's not normally a big deal but the fellow who designed the index template did something that makes it problematic. He is taking the value of segment_2 and passing it through an embed.
So in the first example (index) we are passing the dynamic value "some_url_tile" while in the second example (clinician-map) we are passing "clinician-map". If the embedded template 'html_head' is expecting to get a valid url_title but instead gets the string 'clinician-map' you are likely going to get unexpected results.
Also I don't think we know enough about what you are trying to do to decide if creating a new template is the right approach here. It may be that what you actually need is a new weblog entry or perhaps just a dynamic value inside your existing template.
If it did turn out that a new template is the best approach you could fix the problem I have described by simply replacing segment_2 with segment_3, but I am by no means certain that that is the way you want to go.
I want to create a page that has some Javascript on it. Do I need to
create a new template JUST so I can put some javascript on it?
More specifics would be needed in order to give a solid recommendation but in almost every case, I recommend keeping JavaScript grouped together either in the <head></head> or ideally right before the closing </body> tag if you can get away with it.
Looking at your template code, it appears all the JavaScript is stored in the embeds/html_scripts page. I would add the JavaScript you need to that template. If you only want the JavaScript to appear for certain pages only, I would make use of a conditional (which I'll outline at the end of my answer).
And how do I communicate to EE that I want the page I created to go
with that template?
ExpressionEngine URLs (by default) are assembled as follows:
http://website.com/group/template/url_title
Therefore if you have a page with a url_title of "contact-us", and you wanted that page to use a template in site/pages, you could tell your page to use that template like so:
http://website.com/site/pages/contact-us
That url is obviously fine and dandy for blog articles and such, but it's not that pretty; so ExpressionEngine also enables you to construct "page" based navigation which creates navigation tree based url structures, such as:
http://website.com/contact-us
There are a few third party modules that make it easy to build page navigation such as:
devot-ee.com/add-ons/structure
Using Structure, you specify the default template for each channel and can override the template for each page as well.
I duplicated the page/index template and renamed it to clinician-map
(the same name of the page I created in the publisher). EE didn't like
that and the page subsequently broke. All I want to do is insert one
javascript item, this seems way too inefficient for just one page.
Help??
(using EE 1.6.8) Here is my code from clinician-map template.
There are a number of things I would do different in regards to the template code you provided; however, as a quick fix here's how I would add the one line of JavaScript,
1) Open the embeds/html_scripts template and add the following logic:
{if segment_2 == "my_page_url_title"}
<!-- javascript here -->
{/if}
Note: Here's how segments are determined:
http://website.com/segment_1/segment_2/segment_3
Okay. I ended up just creating a new webblog and new template group and finally it seems like it's working. My javascript is not, but I can figure that out.
Thank you so much for your patience with helping me!

Categories

Resources