AngularJS-使模型变量可用于jQuery

AngularJS - make model variable available to jQuery?

本文关键字:用于 jQuery 变量 模型 AngularJS-      更新时间:2023-09-26

我刚开始使用AngularJS,并试图弄清楚如何从Angular控制器外部轻松引用(绑定?)范围变量。

简单代码:

<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}}绑定到应用程序其余部分可用的inputName var?我有一种丑陋的方法:

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

然后:

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

还有更优雅的吗?

您可以将$window注入控制器并使其在作用域中可用。请参见示例。

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

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

为了更广泛地使用,您可以在$rootScope上提供它。请参阅另一个示例。

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

您还可以从遗留代码中看到调用Angular JS。

对于console.log(),您可以使用

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

请参见示例。

如果你想调试AngularJS应用程序,你可以使用AngularJS Batarang(文本描述和源代码)

我想当你的模型发生变化时,你不会期望你的外部世界会自动更新。相反,你可以对你的模型做一个拉动。

我不喜欢将模型数据与全局变量同步的想法。如果我是你,我会做这个

console.log($("[ng-controller=Ctrl]").scope().yourNameInput);

外部世界中的每个地方都需要访问该模型。