0

I am new to angularJS .. previous I use to work with Jquery.

So I have question in my mind, can we access variable which are declared in angularJS "$scope.options" using jquery.?

    var hostApp = angular.module('hostApp', []);
    hostApp.controller('hostController', function ($scope) {

        $scope.options = [
            { value: '1', label: 'hosting1' },
            { value: '2', label: 'hosting2' },
            { value: '3', label: 'hosting3' }
        ];

        $scope.hostSelected = $scope.options[0];
    });
  • 3
    Please explain **why** you would want to do that. Sounds like a bad idea – devqon Oct 13 '16 at 09:17
  • 1
    could you tell us why you want to do that? what you need it for ? – Exlord Oct 13 '16 at 09:17
  • To push some data to options by using jquery... @devqon –  Oct 13 '16 at 09:18
  • 1
    As I said, sounds like a bad idea. Please explain the use case – devqon Oct 13 '16 at 09:19
  • It is possible to use Angular with jQuery however largely speaking it is not advised. jQuery handles DOM manipulation and that goes against the ethos of angular (using two-way data binding). To manipulate the DOM using angular, directives should be used. You can access the scope using something like `var scope = angular.element($("#elementName")).scope();` and then use `scope.$apply()` to apply the change to the scope itself. – IronAces Oct 13 '16 at 09:19
  • 2
    [The marked answer](http://stackoverflow.com/a/15425015/4108884) on this post may help you. – Samuil Petrov Oct 13 '16 at 09:20

2 Answers2

0

Yes you can using $apply

HTML:

<input type="text" id="txtbox" ng-model="txt" /> <br />
    text is : {{ txt }}
    <br />
    <input type="button" id="btnJq" value="Jquery change" />

Script:

angular.module("md", [])
        .controller("crt", function ($scope) {
            $scope.txt = "text";
        })
$(document).ready(function () {
        $("#btnJq").click(function () {
                var scope = angular.element($("#txtbox")).scope();
                scope.txt = 'Changed';
                scope.$apply();
            })
        })
RJV
  • 287
  • 1
  • 7
  • 20
  • Please don't do this kind of stuff. If you do, don't call yourself an angular developer :) Nevertheless, this answers the OP's question – devqon Oct 13 '16 at 10:35
0

$("#elementId).scope() you can get access to angularJS scope in which you can get all it's variables.

CroMagnon
  • 1,218
  • 7
  • 20
  • 32