43

How to call angular function when data in text box? here is my code

html

<!DOCTYPE html!>
<html xmlns:ng="http://angularjs.org" data-ng-app="flightSearch" lang="en">
    <head>
        <script src="js/jquery-1.9.1.js"></script>
        <script src="js/jquery-ui.js"></script>
        <script src="js/app.js"></script>
    </head>
    <body> 
        <div data-ng-controller="flightSearchController">

<input type="text" data-ng-model="query" data-ng-change="flightSearch()" placeholder="e.g RGN>MDL, KAW>RGN"  id="targetTextField"  />

<input id="options3" type="text" style="display:none;"/>



<select id="options">
  <option value="From" selected>From</option>
  <option value="RGN" ng-click="flightSearch()">RGN</option>
  <option value="NYU" ng-click="flightSearch()">NYU</option>
  <option value="MDL" ng-click="flightSearch()">MDl</option>
  <option value="HEH" ng-click="flightSearch()">HEH</option>
</select>

<select id="options2">
  <option value="To" selected>To</option>
  <option value=">RGN" ng-click="flightSearch()">RGN</option>
  <option value=">NYU" ng-click="flightSearch()">NYU</option>
  <option value=">MDL" ng-click="flightSearch()">MDl</option>
  <option value=">HEH" ng-click="flightSearch()">HEH</option>
</select>

            <ul>
                <li data-ng-repeat="route in filteredItems"> 
                    <div data-ng-bind-html="route.displayRoute"></div>
                </li>
            </ul>

        </div>
    </body>

js

<script src="js/angular.min.js"></script>
    <script src="js/angular-sanitize.min.js"></script>
    <script type="text/javascript">
        function buildPaths(route){
            var points = route.split(">");
            var paths = {};
            for(var i = 0; i < points.length; i++){
                var from = points[i];
                for(var j = i; j < points.length; j++){
                    var to = points[j];
                    if (from != to){
                        if(paths[from + ">" + to]){
                            if(j-i < paths[from + ">" + to][0])
                                paths[from + ">" + to] = [j-i,points.slice(i,j+1).join(">")]
                        }else{
                            paths[from + ">" + to] = [j-i,points.slice(i,j+1).join(">")]
                        }
                    }
                }//for j
            }//for i
            return paths;
        }

        var flightSearch = angular.module('flightSearch',['ngSanitize']);
        flightSearch.controller('flightSearchController', function ($scope){

            // Data definitions, route is actual data,
            // display route is for higlight display purpose only.
            var dataRoutes = [
            {route: "RGN>NYU>MDL>HEH>RGN", displayRoute: "", paths: []},
            {route: "RGN>HEH>KYT>THK>KYT>HEH>RGN", displayRoute: "", paths: []},
            {route: "RGN>MDL>HEH>NYU>RGN", displayRoute: "", paths: []},
            {route: "RGN>MDL>STW>RGN", displayRoute: "", paths: []},
            {route: "RGN>NYU>MDL>MYT>PTO>MYT>MDL>NYU>RGN", displayRoute: "", paths: []},
            {route: "RGN>HEH>NYU>MDL>RGN", displayRoute: "", paths: []},
            {route: "RGN>TVY>MGU>KAW>MGU>TVY>RGN", displayRoute: "", paths: []},
            {route: "RGN>TVY>KAW>TVY>RGN", displayRoute: "", paths: []},
            {route: "RGN>KAW>MGU>TVY>RGN", displayRoute: "", paths: []}];

            // Pre-calculate the possible path the shortest distance
            for(var r = 0; r< dataRoutes.length; r++){
                dataRoutes[r]["paths"] = buildPaths(dataRoutes[r]["route"]);
                dataRoutes[r]["displayRoute"] = dataRoutes[r]["route"];
            }

            // Assign the routes. This is unfiltered origintal data (all)
            $scope.routes = dataRoutes;

            // This is filtered list for dispaly
            $scope.filteredItems = $scope.routes;

            // Search/filter function. This updates filteredItems list
            $scope.flightSearch = function(){


                if($scope.query.length > 6){
                    $scope.filteredItems = [];
                    for(var index in $scope.routes){
                        $scope.routes[index]["displayRoute"] = $scope.routes[index]["route"];
                        if($scope.routes[index]["paths"][$scope.query] !== undefined){
                            var match = $scope.routes[index]["paths"][$scope.query][1];$scope.query
                            $scope.routes[index]["displayRoute"] = $scope.routes[index]["route"].replace(match,"<b>" + match + "</b>");
                            $scope.filteredItems.push($scope.routes[index]);
                        }
                    }
                }else{
                    for(var r = 0; r< $scope.routes.length; r++){
                        $scope.routes[r]["displayRoute"] = $scope.routes[r]["route"];
                    }
                    $scope.filteredItems = $scope.routes;
                }
            }
        });
        flightSearch.filter("highlight",function(){
                return function(text){
                        return text;
                }
        });
    </script>
    <script type="text/javascript">
        $(function() {
$("#options").change(function(){
        setTarget()
});
    $("#options2").change(function(){
        setTarget();
});
    $("#options3").change(function(){
        setTarget();
});
    $("#targetTextField").change(function(){
        setTarget();
});
});

function setTarget(){
    var tmp = $("#options").val();
    tmp += $("#options2").val();
    tmp += $("#options3").val();
    $('#targetTextField').val(tmp);
}


    </script>
</html>

when two select option insert data in text box want to call search function on change.strong text

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Htoo Myat Aung
  • 666
  • 1
  • 7
  • 16

7 Answers7

99

You can access the scope of an angular element if you have an ID tag attached to the same DOM element as the ng-controller:

the DOM:

<div id="mycontroller" ng-controller="mycontroller"></div>

your controller:

function mycontroller($scope) {
   $scope.myfunction = function() {
      //do some stuff here
   }
}

in jquery you do this and it will access that controller and call that function :

angular.element('#mycontroller').scope().myfunction();

Do remember to call

angular.element('#mycontroller').scope().$apply() 

if you update a function variable within scope in myfunction, it will not work otherwise (thanks @andersh)

ganar
  • 627
  • 8
  • 17
btm1
  • 3,866
  • 2
  • 23
  • 26
  • 2
    Why not just `$('#mycontroller').scope().myfunction()`? – cbmanica Jan 09 '14 at 23:22
  • 4
    if i'm going to use an angular method "scope" to access something I am going to use an angular selector angular.element() is angulars version of $() – btm1 Jan 11 '14 at 17:03
  • 2
    You may also need to call scope.$apply() if you update a scope variable in myfunction – andersh Sep 09 '14 at 10:44
  • 2
    if `ng-controller="mycontroller as child"` then access with `angular.element('#mycontroller').scope().child.myFunction();` - see http://stackoverflow.com/a/32605033/165673 – Yarin Apr 20 '16 at 13:27
  • I have these doubts. 1)What is the function of $apply() ? and how does it work? 2)Should the $apply be made from jQuery or angular? – Vishnu Y S Dec 29 '16 at 11:36
  • Thanks about `Do remember to call $apply()`. It works finally. – AechoLiu Oct 26 '17 at 05:44
16

if you use in your code something like this

<div id="mycontroller" ng-controller="mycontroller as child"></div>

instead of

<div id="mycontroller" ng-controller="mycontroller"></div>

the access will be

angular.element('#mycontroller').scope().child.myFunction();

instead of

angular.element('#mycontroller').scope().myFunction();

in every case you also need the call

angular.element('#mycontroller').scope().$apply();
Zauker
  • 2,344
  • 3
  • 27
  • 36
7

for accessing scope element of the controller

angular.element(document.getElementById('controllerId')).scope().scope_variable_array.push(item);

for accessing controller function

angular.element(document.getElementById('controllerId')).scope().function_name();

controllerId : tag id where the ng-controller is defined in HTML

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
Pruthviraj
  • 1,689
  • 2
  • 14
  • 18
4

I use something like this:

var $scope = angular.element($('[ng-controller]')).scope()

And manipulate the $scope variable. You can check in the console

Ivan-San
  • 771
  • 1
  • 5
  • 22
4

I refer to this post, assign function to global object window.

            // In angularJS script
            $scope.foo = function() {
                console.log('test');
            };
            $window.angFoo = function() {
                $scope.foo();
                $scope.$apply(); 
            };

            // In jQuery
            if (window.angFoo) {
                window.angFoo();
            }
AechoLiu
  • 17,522
  • 9
  • 100
  • 118
1

I use this code and work well.

 var $scope = angular.element($('[ng-controller="MapCtrl"]')).scope();

and thanks to @Ivan-San answers.

porya ras
  • 458
  • 5
  • 15
0

You can put Jquery code into AngularJS controller like

    $scope.shipchange = function (SelectedShipId ) {
        alert('ShipId =' + SelectedShipId );
    }

    $("#Ships").change(function () {

        SelectedShipId = $("#Ships").val();
        $scope.shipchange(SelectedShipId );
    })
user1575120
  • 301
  • 2
  • 4