javascriptjqueryangularjsangularjs-scope

Convert Javascript function to AngularJS function


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!


Solution

  • 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