Use $scope variable in a JavaScript function called from the HTML code - AngularJS

流过昼夜 提交于 2019-12-08 07:52:30

问题


I'm using Angular and I'm trying to get $scope to use it in a JavaScript function. Here is an example:

I have an html tag something like this:

<a id="doSomething" onclick="javascript: doSomething(this);">Do Something</a>
<div ng-show="flag">Click!</div>

and a JavaScript function something like this:

function doSomething(obj) {
    //$scope.flag = true;
    return true;
}

What I want is to use the $scope in this function. I haven't found a way to inject it. The thing is that I must use this way to call the function. Do you have any solution to this? I would appreciate it!

Thanks!


回答1:


If you really have to.. here's how:

HTML:

<a onclick="doThing(this);">Do it!</a>

JS:

function doThing(el) {
  var $scope = angular.element(el).scope();
  $scope.thing = newVal;
  $scope.$apply(); //tell angular to check dirty bindings again
}

Make sure to read the docs for angular.element: http://docs.angularjs.org/api/angular.element And for scope.$apply: http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply

What is your use case, though? There might be a better way.




回答2:


You can also do it inline:

JS:

$scope.doThis = function(str){
     alert(str);
     $scope.$apply();
}

HTML:

<button onclick="angular.element(this).scope().doThis('TEST');"></button>

Caveat - scope nesting may affect the results but if the angular code is in the parent controlled this works fine out the box




回答3:


This is the same as @Andy's answer, but I mention it in case people want to see how to get the $scope from an event instead of this:

HTML:

<a onclick="doThing(event);">Do it!</a>

JS:

function doThing(ev) {
  var $scope = angular.element(ev.srcElement).scope();          
  $scope.flag = true;
  $scope.$apply(); //tell angular to check dirty bindings again
}



回答4:


You should call angular ng-click for this and then pass scope from there.

Here is the example i created for you. http://plnkr.co/edit/UDLJYuZhR4yfiocSPjKJ

Mark it as answer if it solves your problem.



来源:https://stackoverflow.com/questions/14237551/use-scope-variable-in-a-javascript-function-called-from-the-html-code-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!