Search code examples
javascriptangularjsfunctionangularjs-scopeangular-controller

Load data when click on button


I am searching how to call a function from a controller with parameters in textbox. This is my HTML code :

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="controllerInput.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-app="appName">
    <input type="text" id="idName" name="idName" ng-model="modelName" ng-controller="controllerName">
    <button class="btn btn-default" ng-click="functionName()">Execute</button>
  </body>

</html>

This is the controller :

d3DemoApp.controller('controllerName',function($rootScope,$scope) {
    $scope.modelName = '';
    $scope.functionName = function () {
        myFunction($scope.modelName);
    };
});

And app.js :

function myFunction(concatURL){
    //loadData('URL' + concatURL);
    console.log("Function successfully called !");
}

The problem is on my app file, I have a function loadData which must be call but it is in a controller named controllerApp and my function myFunction is not know if it is in controllerApp. Hope you will can help me, thanks a lot.


Solution

  • You've made two mistakes in your code

    1. You have not declared the module appName before trying to use it.
    2. You have applied the ng-controller just to the input element, not to the element containing both the input and the button.

    To fix the first you need this line before trying to use the module:

    var variableName = angular.module("appName",[]);
    

    To fix the second, move the ng-controller element up:

    <body ng-app="appName" ng-controller="controllerName">
        <input type="text" id="idName" name="idName" ng-model="modelName">
       <button class="btn btn-default" ng-click="functionName()">Execute</button>
    </body>