我刚开始使用 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/