使用$作用域变量从HTML code称为JavaScript函数 - AngularJS [英] Use $scope variable in a JavaScript function called from the HTML code - AngularJS

查看:97
本文介绍了使用$作用域变量从HTML code称为JavaScript函数 - AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的角度,我试图让$范围在JavaScript函数中使用它。下面是一个例子:

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

我有一个HTML标签是这样的:

I have an html tag something like this:

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

和JavaScript函数是这样的:

and a JavaScript function something like this:

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

我要的是使用$范围在此功能。我还没有找到一种方法来注入它。
事情是,我必须用这种方式来调用该函数。你有什么解决办法吗?我想AP preciate呢!

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!

谢谢!

推荐答案

如果你真的有..方法如下:

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
}

请务必阅读angular.element文档: http://docs.angularjs.org /api/angular.element
。而对于范围$适用于: http://docs.angularjs.org/api/ng 。 $ rootScope.Scope#$适用

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.

这篇关于使用$作用域变量从HTML code称为JavaScript函数 - AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆