0

I have a text field that is being controlled by jQuery/external Javascript. I'm looking to add something that causes the text field to also be shown on another element. I'm looking to develop something like this but I know this isn't how you program it:

<span id="reading" ng-bind="reading"></span>
<div ng-bind="reading"></div>
<script>
$('#reading').text('100');
</script>

The desired output is to have 100 displayed in both the span and the div.

0

2 Answers 2

1

So rather that going for jQuery method to change the text, I'd change the reading scope value.

$scope.reading = '10'

But I know you wanted to call that method from external context of angular, so below is the way by which you could access the scope by having DOM query on ng-controller name .

var scope = angular.element('[ng-controller=ctrl]').scope();
scope.reading = '10'
scope.$apply(); // to update bindings.
9
  • I like it. Is also works for dynamic controllers? routes for example?
    – Dvir
    Commented Nov 11, 2015 at 19:01
  • @Dvir if you pass the controller name dynamically to this method then it could work.. Commented Nov 11, 2015 at 19:03
  • Hi.. I already have existing code that is not AngularJS -- a lot of it. I'm trying to use AngularJS to avoid using more of the old code Commented Nov 11, 2015 at 19:04
  • Is there anyway to watch the .text() of #reading with simple AngularJS directives? Commented Nov 11, 2015 at 19:05
  • 1
    @Dvir if its ngRoute router in app then he could use angular.element('[ng-view]').scope() there in a place.. Commented Nov 11, 2015 at 19:15
0

If you want angular to detect your changes. you should do that in $apply(). You have to create a directive on those elements. inside that directive write a link function

link:function(scope,ele,attrs,ngModel){

      scope.$apply(update);  //trigger digest cycle 

        function update() {
              ngModel.$setViewValue(100); //changes model
              ngModel.$render();  //updates view
        }
}
6
  • is there anyway of doing this without adding a new directive? I was hoping I could do something using HTML directives Commented Nov 11, 2015 at 19:18
  • It's not about directive. the script which is going to change the value should be inside $apply(). otherwise angular wont detect the change
    – lch
    Commented Nov 11, 2015 at 19:19
  • so AngularJS can not detect DOM changes made by jQuery? Commented Nov 11, 2015 at 19:21
  • May be you are using angularJs for some parts of your application. once you pick up angularJs, better stick with that. forget Jquery way of manipulating data and DOM
    – lch
    Commented Nov 11, 2015 at 19:22
  • It is recommended that DOM changes should be made only in directives
    – lch
    Commented Nov 11, 2015 at 19:23

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.