javascript - AngularJS - 使模型变量可用于 jQuery?

标签 javascript jquery angularjs

我刚开始使用 AngularJS,并试图找出如何从 Angular Controller 外部轻松引用(绑定(bind)?)范围变量。

简单代码:

<div ng-controller="Ctrl">
  <label>Name:</label>
  <input type="text" ng-model="yourNameInput" placeholder="Enter a name here">
  <input type="button" onClick="console.log(inputName);">
  <hr>
  <h1 ng-bind-template="Hello, {{yourNameInput}}"></h1>
</div>

我如何将 {{yourNameInput}} 绑定(bind)到 inputName var,以便我的应用程序的其余部分可用?我设法做到了一种丑陋的方式:

$scope.change = function() { inputName = $scope.yourNameInput; }

然后:

<... ng-change = "change()">

还有更优雅的吗?

最佳答案

你可以注入(inject)$window进入您的 Controller 并使其在示波器上可用。参见 example .

function Ctrl($scope, $window) {
    $scope.window = $window;
}​

...

<input type="text" ng-model="yourNameInput" placeholder="Enter a name here" ng-change="window.yourName = yourNameInput">

为了更广泛地使用,您可以在 $rootScope 上提供它.再看一个example .

angular.module('myApp', [])
    .run(function($rootScope, $window){
        $rootScope.window = $window;
    });

你还可以看到Call Angular JS from legacy code .

对于 console.log() 你可以使用

<input type="button" onClick="console.log('{{yourNameInput}}');" value="Log">

参见 example .

如果你想调试 AngularJS 应用程序,你可以使用 AngularJS Batarang ( textual description and source code )

关于javascript - AngularJS - 使模型变量可用于 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12333882/

相关文章:

javascript - 为什么 videojs 按空格键切换全屏,而不是切换播放/暂停

jquery:测试输入变量是否为dom元素

javascript - 成功注入(inject)后在指令 View 中显示常量

javascript - CKEditor + Protractor : Testing with Protractor can't find CKEditor instance

javascript - AngularJS:重新分配对象与在 Controller 中替换对象

javascript - 使用 Javascript 将段落从外部 HTML 页面插入到另一个 HTML 页面

javascript - Chrome 中的慢 cors 预检选项请求

javascript - 最轻的 DOM 对象

javascript - 延迟改变一个类(class)的背景颜色

javascript - JQuery 无法从动态创建的字段中获取输入值