在 AngularJS 中是否可以在经典的 javascript 函数中使用数据绑定? [英] Is it possible in AngularJS to use data bindings inside a classic javascript function?

查看:24
本文介绍了在 AngularJS 中是否可以在经典的 javascript 函数中使用数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Angularjs 数据绑定 功能的问题.

如果我写:

你好{{name}}!

而且我在 controller.js 中有类似的东西:

$scope.name = 'Bruno';

结果将是你好布鲁诺!"......这太棒了!现在我编辑了模板:

你好!

而且我还在关闭正文之前添加了这个 javascript 函数:

<script src="js/app.js"></script><script src="js/services.js"></script><script src="js/controllers.js"></script><script src="js/filters.js"></script><script src="js/directives.js"></script><script type="text/javascript">功能填充名称(主题){$("#name").text("你好" + 主题);}填充名称({{名称}});//这会抛出SyntaxError: invalid property id"

<小时>

所以我的问题是:

在 AngularJS 中是否可以在经典的 javascript 函数中使用数据绑定?

<小时>

更新:

//我改了:fillName({{name}});和:fillName('{{name}}');

这解决了错误......但仍然没有出现名称......我仍在努力......

随时欢迎提出建议!

解决方案

[更新] 好吧,看来我误解了您的问题,因为您似乎已经解决了您的问题,但也许其他人会根据以下信息偶然发现此信息问题的标题.

<小时>

我将以以下警告作为我的答案的前缀:如果您正在编写 AngularJS 应用程序,您将希望使用 Angular 提供的功能(如指令)来执行此类操作,而不是在 Angular 应用程序之外生命周期和编写全局函数等.但是,为了对问题的学术回答感兴趣,这里是.

概述

您尝试在此处访问的 Angluar 魔法基于一些设施:

范围(文档)

Scopes 为 Angular 表达式(你放在属性和双卷曲中的东西)提供了一个上下文,并提供了必要的函数来观察在该上下文中这些表达式的评估变化.例如,Scope#$watch 允许您注册一个回调,该回调在表达式的评估发生变化时执行.

$interpolate(docs)

Interpolate 获取一个字符串,该字符串可以包含双花括号内的表达式,并将其转换为一个新字符串,并将表达式结果插入到原始字符串中.(调用 $interpolate(str) 返回一个函数,当针对提供作用域的对象调用该函数时,返回一个字符串.)

组合起来

在编写 Angular 应用程序时,您通常不必担心这些细节——您的控制器会自动传递一个范围,并且您的 DOM 文本会自动插入.由于您试图在 Angular 应用程序的生命周期之外访问这些内容,因此您必须跳过其中一些以前隐藏的圈套.

angular.injector(文档)

当您使用 app.controllerapp.factory 等在模块上注册服务、过滤器、指令等时,您提供的函数将被调用由注射器.Angular 在 Angular 应用程序中为您创建一个,但由于我们没有使用它,您需要使用 angular.injector 自己创建一个.

一旦你有了一个注入器,你就可以使用 injector.invoke(fn) 来执行函数 fn 并注入任何依赖项(比如 $interpolatecode>) 用于函数内部.

一个简单的例子

这是一个非常基本的例子

  • 提供输入和变量之间的双向数据绑定
  • 使用 $interpolate
  • 将数据绑定到 HTML 视图中

名称:<button id="setname">将名称设置为 Bob</button><div id="问候语"></div>

var injector = angular.injector(['ng']);注入器.调用(函数($rootScope,$interpolate){var scope = $rootScope.$new();var makeGreeting = $interpolate("Hello {{name}}!");scope.$watch('name', function() {var str = makeGreeting(scope);$("#greeting").text(str);$("#name").val(scope.name);});var handleInputChange = function() {范围.$应用(函数(){scope.name = $('#name').val();});};var setNameToBob = 函数(){范围.$应用(函数(){scope.name = "鲍勃";});};$("#name").on('keyup', handleInputChange);$("#setname").on('click', setNameToBob);处理输入更改();});

这是一个演示该技术的 jsFiddle:http://jsfiddle.net/BinaryMuse/fTZu6/

I've a question about Angularjs data binding feature.

If i write:

<div>Hello {{name}}!</div>

and i've in the controller.js something like:

$scope.name = 'Bruno';

The result will be "Hello Bruno!"... and this is wonderful! Now i edited the template:

<div>Hello <span id="name"></span>!</div>

and i also added this javascript function just before close the body:

<script src="lib/angular/angular.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>

<script type="text/javascript">

  function fillName(subject) {
    $("#name").text("Hello " + subject);
  }

  fillName({{name}}); // this throws "SyntaxError: invalid property id"

</script>
</body>


So my question is:

Is it possible in AngularJS to use data bindings inside a classic javascript function?


UPDATE:

// i changed: fillName({{name}}); with:
fillName('{{name}}');

and this solved the error... but still the name doesn't appear... i'm still working on this...

suggestions always welcome!

解决方案

[Update] Well, it appears that I misunderstood your question, as you seem to have solved your issue, but perhaps other people will stumble upon this information based on the title of the question.


I will prefix my answer with the following caveat: if you're writing an AngularJS application, you'll want to use the features Angular provides, like directives, for doing this kind of stuff, rather than going outside the Angular application lifecycle and writing global functions, etc. In the interest of the academic answer to the question, however, here it is.

Overview

The Angluar magic that you're trying to get access to here is based on a few facilities:

Scope (docs)

Scopes provide a context for Angular expressions (the things you put in attributes and the double curlies) and provide the functions necessary to watch for changes in the evaluation of these expressions in that context. For example, Scope#$watch allows you to register a callback that is executed whenever the evaluation of an expression changes.

$interpolate (docs)

Interpolate takes a string that can include expressions inside double curlies and turns it into a new string with the expression results interpolated into the original string. (Calling $interpolate(str) returns a function which, when called against an object that provides scope, returns a string.)

Putting it Together

When writing an Angular app, you often don't have to worry about these details--your controllers automatically get passed a scope, and your DOM text is automatically interpolated. Since you're trying to access these things outside of the lifecycle of an Angular app, you'll have to jump through some of these previously hidden hoops.

angular.injector (docs)

When you register services, filters, directives, etc. on a module using app.controller, app.factory, and so forth, the functions you provide are invoked by the injector. Angular creates one for you in an Angular app, but since we're not using one, you'll need to use angular.injector to create one yourself.

Once you have an injector, you can use injector.invoke(fn) to execute the function fn and inject any dependencies (like $interpolate) for use inside the function.

A simple example

Here's a very basic example that

  • Provides two-way data binding between an input and a variable
  • Provides data binding into an HTML view using $interpolate

Name: <input id="name" type="text" autocomplete="off">
<button id="setname">Set name to Bob</button>
<div id="greeting"></div>

var injector = angular.injector(['ng']);

injector.invoke(function($rootScope, $interpolate) {
  var scope = $rootScope.$new();
  var makeGreeting = $interpolate("Hello {{name}}!");

  scope.$watch('name', function() {
    var str = makeGreeting(scope);
    $("#greeting").text(str);
    $("#name").val(scope.name);
  });

  var handleInputChange = function() {
    scope.$apply(function() {
      scope.name = $('#name').val();
    });
  };

  var setNameToBob = function() {
    scope.$apply(function() {
      scope.name = "Bob";
    });
  };

  $("#name").on('keyup', handleInputChange);
  $("#setname").on('click', setNameToBob);
  handleInputChange();
});

Here is a jsFiddle that demonstrates the technique: http://jsfiddle.net/BinaryMuse/fTZu6/

这篇关于在 AngularJS 中是否可以在经典的 javascript 函数中使用数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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