How To Access Function From Outside AngularJS - javascript

I have absolutely never used AngularJS -
I am able to handle all parts of someone else's script - but am lost with a newb idea of accessing the functions outside of the Class? Or whatever it is called 0_o - I have tried to look this up - but I just get lost.
The script Im working on is like this:
app.controller("searchFormController", function($scope,$http){
$scope.getSomeDetails = function(filter){
alert("you are doing stuff in this function");
}
})
The function is typically called from a form outside of the script - like this:
<select id="transmissions" name="transmission" ng-model="transmission" ng-change="getSomeDetails(true)">
When the above form element is selected - the function getSomeDetails is called properly.
Now I simply want to call the same function with a text link instead.
I have tried:
<span onClick="getSomeDetails(true)">Get Details </span>
Not sure what I am doing wrong -
I just want to call the same function but using a text link?
Thanks for your help.

app.controller("searchFormController", function($scope,$http){
$scope.getSomeDetails = function(filter){
alert("you are doing stuff in this function");
};
});
Here searchFormController is the your angular function.So attached this function to html template with ng-controller attribute. functions and variable mentioned inside this searchFormController will be available to the template in which you have bind that function with ng-controller.
Your getSomeDetails function is in this searchFormController. So in html template where you wants to call this function before that you needs to bind the controller to it's parent element or to that element so that function scope is available where you needs to call.
Here you have to call function on the click of link so use ng-click. and call the function.
Your span tag should be like this.
<span ng-controller="searchFormController" ng-click="getSomeDetails(true)">Get Details </span>

<span ng-click="getSomeDetails(true)">Get Details</span>

Related

ng-click Vs click event

I am working on a website based on angular js.
Currently, I have written about 5000 line code in angular js.
So I have to make some changes without touching my angular js.
I want something like this:
$(document).on('click','#buttonid',function(){
//performing some necessary task then call ng-click method
ngclickmethod();
});
HTML Code:
<a ng-click="ngclickmethod()" id="buttonid">
Please advise how can I achieve that.
Many Thanks
So it looks like you are trying to call an angular function outside of angular. Try this..
angular.element(document.getElementById('yourControllerElementID')).scope().ngclickmethod();
this will call the method you want. Be sure the controller element ID is the controller that contains the ngclickmethod function

Expandable textarea field for chat app using angular directive

I'm using angular/bootstrap and have a particular directive which functions as the actual chat input box to my app. I've gotten the more important expanding behavior done, except I can't quite figure out how to do three things in specific...
Here is the fiddle
1) I need to have the enter key submit the text inside the textarea (using the button of the form is optional, feel free to remove it). I'm getting the following error in my console: "Uncaught ReferenceError: $ is not defined" (lack of knowledge of js structure here).
2) Since I'm using angular, where I should include the custom script? Probably not inline inside tags in the directive...maybe inside controllers.js? What's the best practice for that?
3) The ajax call inside the script this.form.sendThought();, can controllers.js be accessed from the script? I guess #2 above needs to be in a place such that I could access this function...
Here is the directive:
<div class="clear" ng-show="allowInput">
<form role="form">
<div class="input-group">
<div class="textarea-container" id="txtCont">
<textarea ng-model="rawResponse"></textarea>
<div class="textarea-size"></div>
</div>
<span class="input-group-btn">
<button class="btn btn-lg" type="button" ng-click="sendThought()">send</button>
</span>
</div>
</form>
</div>
Script:
var textContainer, textareaSize, input;
var autoSize = function () {
textareaSize.innerHTML = input.value + '\n';
};
document.addEventListener('DOMContentLoaded', function() {
textContainer = document.querySelector('.textarea-container');
textareaSize = textContainer.querySelector('.textarea-size');
input = textContainer.querySelector('textarea');
autoSize();
input.addEventListener('input', autoSize);
});
$('#txtCont').keydown(function() {
if (event.keyCode == 13) {
this.form.sendThought();
return false;
}
});
You don't have jQuery included (which is what the $ global object usually means here). You can either include jQuery or do this with vanilla JS. (Even better, use jqLite from inside the Angular directive!)
Here's what a keyup event looks like with plain JS. You don't have to name the function like I did if you prefer to pass an anonymous function in. I prefer to name them so I can modify later if I need to. (I also think it's cleaner)
document.getElementById('chat').onkeyup = keyPressedChat;
http://jsfiddle.net/k0kyu5t7/
I put that together real quick to help give you an idea about what I mean by using vanilla JS outside the context of your app.
I noticed a couple more problems looking at it a second time (besides not including jQuery):
You should be listening for keydown events on the textarea element instead of the parent div. It's possible to capture keypress events that you might not want unless you point to the text area specifically.
You should be passing the event into your anonymous function callback that you're attaching to the handler.
The answer to your #2 is far too broad for a quick discussion here. There are a lot of opinionated ways on how to organize your files in an Angular app. I personally like to break things down by components and then drop them inside folders like that. Your "chat-directive" could live inside [Root] -> [Chat] -> [Directives] -> chat.js. That's just one way.
As for your #3, it depends on what you want here. You can call services/factories from your directives, which is where your ajax calls should be anyway. If you want your directive to be more modular, then one option might be to pass a method through the directive itself (via the view).

emberjs call action from onclick

I have a model which will return a block of text, I want an alert that will define particular words within that block of text. So I want to add a link next to the particular word that will call an action that creates the alert.
I can't use handlebars action method as the page will already be rendered. So when I'm pushing my model I want to include something like this:
<button id='definition' onclick='newAlert()'>i</button>
There may be a number of words that need the definition in a single block of text so I'd need to send an identifier also.
My question is, is it possible to call an action in this way?
Thanks for any help.
Whenever it is required to access ember entities from the DOM using pure js, for example when required to handle an onclick js event and delegate it to ember entities, it is possible to do something like
http://emberjs.jsbin.com/mimuwale/1/edit
js
App = Ember.Application.create();
function getView($el){
return Ember.View.views[$el.closest(".ember-view").attr("id")];
}
function newAlert(el){
getView($(el)).get('controller').send('newAlert',el.id);
}
App.IndexView=Ember.View.extend();
App.IndexController=Ember.Controller.extend({
actions:{
newAlert:function(buttonId){alert('clicked button:'+buttonId);}
}
});
hbs
<script type="text/x-handlebars" data-template-name="index">
<button id='definition' onclick='newAlert(this)'>test</button>
</script>

Passing a parameter to a Javascript function using data attributes in an <a> tag in MVC 5

I am building an MVC 5 web app using Visual Studio 2013.
I am trying to create a list of Courses using anchor tags which when clicked will pass as a parameter the selected Course to a Javascript function. The Javascript function will in turn use Ajax to call a second function to retrieve a list of Students enrolled on the selected Course.
In the View I have:
#model IEnumerable<School.Models.Course>
...
#foreach (var item in Model)
{
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="#item.CourseName">#item.CourseName</a>
}
The Course list gets created as expected:
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="Chemistry">Chemistry</a>
<a class='selectedCourse' onclick='JavaScript:selectedCourse()' data-cname="Physics">Physics</a>
My Javascript function is defined as follows:
function selectedCourse() {
var selectedCourseName = $(this).data('cname');
}
The code reaches the Javascript function but the value of selectedCourseName is always 'undefined'.
Am I missing something really basic for this to work?
Any help would be greatly appreciated.
Walter
The reason that it's not working is because the context of this on an inline event handler is not the element itself, but the window element. Change your code so that the handler is applied separately from your markup, this is a best practice anyway, and the context will be correct.
$('.selectedCourse').on('click', function(e) {
e.preventDefault();
var selectedCourseName = $(this).data('cname');
...
});
An alternative, and one I don't recommend, is to add a parameter to your inline handler and pass this as the parameter. The value of the parameter will be the element that was clicked.
Don't do this!
See examples at http://jsfiddle.net/cJZpK/

Jsp with javascript parameter inside javascript onclick

I would like to insert a call to a function to get a parameter for my JavaScript onclick function. What I would like to do is something like:
<input class="refreshbutton"
type="button"
id="searchUfficiPopup"
onClick="javascript:postColorbox('/DeliDete/searchUfficiPopupBySettoreId', **'&settoreIdKey=${javascript:getSettoriId()}'**, 'tabUfficiForm', 'initScriptUffici')"
value="<fmt:message key="navigation.searchUffici"/>" />
This way Eclipse tells me the function javascript:getSettoriId() is undefined. I defined this function in an external .js file, loaded at runtime with jQuery's .getScript, so I would not like to insert it into the jsp (anyway I tried to insert it into the jsp but the IDE still says that the function is not defined).
The function postColorbox is defined as:
function postColorbox(url, parameters, formName, initScript)
The function getSettoriId() returns the value of a previously entered form element, Settori, which I need to perform a restricted query (I need to obtain all Uffici entities related to the selected Settori entity)
Told this, I would like to ask you experts:
Is it even possible to use a JavaScript function as a parameter of an onclick JavaScript function?
If I put this function to be called in an external .js file will the jsp be able to see it and call it?
Thank you all for your help!
Andrea
Remove the onClick on your <input> and do it with a jQuery event handler instead:
$('#searchUfficiPopup').click(function() {
var settoriId = getSettoriId();
postColorbox('/DeliDete/searchUfficiPopupBySettoreId',
'&settoreIdKey=' + settoriId,
'tabUfficiForm',
'initScriptUffici');
return false;
});
Calling functions from inside the HTML element is not a preferred way. If you can - just assign the element an id or class, and then add a listener to it using javascript on page load.
This way you don't have your data and operations mixed. It will be also easier to modify the code, as your code will be located in js files.

Categories

Resources