Reputation: 1753
I wrote a simple javascript function that switches between two div elements. Like so:
function goToResults() {
document.getElementById("services").style.display = "none";
document.getElementById("results").style.display = "block";
}
As I am learning Angular, I want to convert that to an Angular function in app.js. Can I do the following?
$scope.goToResults = function () {
$scope.getElementById("services").style.display = "none";
$scope.getElementById("results").style.display = "block";
}
Thanks!
Upvotes: 2
Views: 8253
Reputation: 1417
It's technically possible to use
$scope.goToResults = function () {
document.getElementById("services").style.display = "none";
document.getElementById("results").style.display = "block";
}
However, this isn't a very 'angular' way of doing this. A more 'angular' route is described in the answers to this question. Generally speaking, referring to specific elements isn't the 'angular' way; it seeks to instead have a set of javascript utilities readily available for the (processed) HTML to use, such as directives, which are essentially new elements or attributes for use in HTML. The implementation of the directives has no direct coupling to the elements it modifies with the use of those attributes or elements, which makes angular much more reusable and, in my and many others' opinions, easier to read and write once you get used to it.
Upvotes: -2
Reputation: 1348
There are a few issues with the piece of code that you provided.
Firstly there are no such thing as AngularJS only functions. They are the same as any other javascript function. If you want to use a "javascript" function inside AngularJS's scope, you can do the following:
function goToResults() {
...
}
$scope.goToResults = goToResults;
Secondly, it's considered a bad practice to handle DOM manipulation inside a controller. Use directives instead.
Thirdly, from what I understand you want to show or hide a div based on some event. There are some in-built features that do that exact thing (ng-show, ng-hide, ng-if).
You seem to lack some fundamental knowledge about Javascript & AngularJS, and I'd suggest going through the tutorials given example by Angular's own documentation https://docs.angularjs.org/tutorial
Upvotes: 3