作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图创建一个与进度条相对应的 AngularJS 组件。这是为此问题创建的 JSFiddle http://jsfiddle.net/Lvc0u55v/6725/
这是我的应用程序和组件定义:
var myApp = angular.module('myApp',[]);
myApp.controller('TestController', function($scope) {
$scope.total = 20;
$scope.count = 15;
$scope.changeTotal = function(value){$scope.total += value};
$scope.changeCount = function(value){$scope.count += value};
});
myApp.component('progressBar', {
bindings: {
percentage: '=',
},
controller: function() {
this.width = this.percentage * 100;
},
template: '<div class="progressBar">\
<div class="inner" style="width: [[$ctrl.width]]%"></div>\
</div>',
});
以及以下 HTML 代码:
<div ng-app="myApp">
<div ng-controller="TestController">
Total: {{total}}, <button ng-click="changeTotal(-1)">-</button><button ng-click="changeTotal(+1)">+</button><br/>
Count: {{count}}, <button ng-click="changeCount(-1)">-</button><button ng-click="changeCount(+1)">+</button><br/>
Percentage: {{count / total}}%<br/>
<br/>
<progress-bar percentage="{{count / total}}"></progress-bar>
</div>
</div>
尽管在组件 Controller 中定义了 width
属性,AngularJS 在定义的模板中找不到它。
由于我刚刚开始学习 AngularJS,因此很难有效地调试此代码。
最佳答案
由于您在组件中使用 =
(双向绑定(bind)),因此您不应在百分比属性值中使用 {{}}
。直接计算的值可以传递给用 ()
括号括起来的 percentage
属性。
在绑定(bind)百分比显示进度条时,您可以使用 ng-style
指令以及已传递给组件绑定(bind)的
.$ctrl.percentage
值
HTML
<progress-bar percentage="{{(count / total)}}"></progress-bar>
指令模板
template: '<div class="progressBar">\
<div class="inner" ng-style="{ width: $ctrl.percentage+\'%\'}"></div>\
</div>',
关于javascript - 如何在 AngularJS 组件中定义新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38311863/
我是一名优秀的程序员,十分优秀!