javascript - 如何在 Angular JS 中访问控制器函数中的内部脚本 $scope 值
问题描述
这是带有内部脚本的 HTML
<html>
<body ng-controller="test">
<span> {{data.name}} </span>
<input ng-model="data.name">
<hidden id="test" ng-hide="true"></hidden>
</body>
<script>
var $scope = angular.element(document.getElementById('test')).scope();
$scope.data = {
name : test;
};
<script>
</html>
这是控制器
app.controller('test', function($scope) {
$scope.data = {};
console.log($scope.data.name) //outputs undefined
})
我希望将内部脚本数据输入控制器。它打印未定义。我在控制器中定义了一个对象,但在内部脚本中进行了更新。如果假设我从 HTML 打印或绑定数据,它不会在控制器范围对象中更新。有什么解决方案吗?
解决方案
您是否尝试从控制器中获取它?或者,也许您将需要更多 angularjs 方法。我创建了两个示例:一个用于初始化控制器中的数据,另一个用于 console.log 的niceLittleValue
.
(function(angular) {
'use strict';
var myApp = angular.module('niceExample', []);
myApp.config(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
}]);
myApp.controller('test', ['$scope', function($scope) {
$scope.data = [];
$scope.data.name = 'test';
$scope.data.anotherTest = angular.element(document.querySelector('#anotherTest'));
console.log($scope.data.anotherTest[0]);
}]);
})(window.angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<html ng-app="niceExample">
<body ng-controller="test">
<input ng-model="data.name" ng-model-options="{debounce: 500}">
<span> {{data.name}} </span>
<hidden id="test" ng-hide="true"></hidden>
<hidden id="anotherTest" value="niceLittleValue" ng-hide="true"></hidden>
<span> {{data.anotherTest}} </span>
</body>
</html>
推荐阅读
- sqlite - SQLite 中的时差
- python - python argparse 最多 3 个位置参数,每个位置参数的可选标志
- docker - oraclelinux 上的 Oracle 钱包
- r - 添加前导零以将数字调整为正确的格式
- travis-ci - npm install 在 Travis CI 中工作,但在 GitHub Actions 中失败
- python - Python Selenium 和 BS
- github - 删除 VSC 项目和 Github 之间的连接
- python - bash 中的 subprocess.call() exec 命令,但我使用的是 zsh?
- react-native - 垂直居中滚动视图
- html - 图片无法显示