我正在尝试让应用能够根据来自 Google 字体的字体列表设置部分文本的字体。
这是我所拥有的:
<ul ng-init='headerFont="mono"'>
<li ng-repeat='font in fonts' style='font-family: {{font}};' ng-click='headerFont = font'>{{font}}
</li>
</ul>
然后是:
<h1 style='font-family: {{headerFont}};'>Header</h1>
在我的 js 文件中的 Controller 中:
$scope.fonts = [...an array of font names...]
最初,而不是 ng-repeat
在 <li>
,我正在使用:
<select ng-model='headerFont' style='font-family: {{headerFont}};'>
<option ng-repeat='font in fonts' style='font-family:{{font}};'>{{font}}
</option>
</select>
这完全符合我的预期。但我想尝试使用可滚动列表而不是下拉菜单,因为 <select>
移动浏览器上的菜单不支持更改单个选项的字体,对我来说重要的是在选择之前能够预览字体。我想我可以使用 ng-click
设置 headerFont
的值,但它什么也没做(控制台或任何地方都没有显示错误。什么也没发生。)有人知道为什么吗?
最佳答案
问题是 ngRepeat 为每次迭代创建子作用域,因此 ngClick 实际上更改了本地子 headerFont
变量。
一种可能的解决方案是显式引用父作用域:
var app = angular.module('demo', []);
app.controller('demoController', function($scope) {
$scope.fonts = ['Arial', 'Times New Roman', 'Verdana', 'mono'];
})
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<div ng-app="demo" ng-controller="demoController">
<h1 style='font-family: {{headerFont}};'>Header</h1>
<ul ng-init='headerFont="mono"'>
<li ng-repeat='font in fonts' style='font-family: {{font}};' ng-click='$parent.headerFont = font'>{{font}}</li>
</ul>
</div>
关于javascript - AngularJS:为什么 ng-click 不会将变量设置为从 ng-repeat 获得的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31634740/