如何在 AngularJS 组件中定义一个新变量
How to defined a new variable in AngularJS component
我试图创建一个对应于进度条的 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>
尽管在组件控制器中定义了width
属性,AngularJS在定义的模板中找不到它。
因为我刚开始学习,所以我很难有效地调试这段代码AngularJS。
由于您在组件中使用 =
(双向绑定),因此您不应在百分比属性值中使用 {{}}
。直接计算的值可以传递给用 ()
括号包裹的 percentage
属性。
虽然显示进度条的绑定百分比,您可以使用 ng-style
指令和 $ctrl.percentage
值,该值已传递给组件 bindings
。
HTML
<progress-bar percentage="{{(count / total)}}"></progress-bar>
指令模板
template: '<div class="progressBar">\
<div class="inner" ng-style="{ width: $ctrl.percentage+\'%\'}"></div>\
</div>',
我试图创建一个对应于进度条的 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>
尽管在组件控制器中定义了width
属性,AngularJS在定义的模板中找不到它。
因为我刚开始学习,所以我很难有效地调试这段代码AngularJS。
由于您在组件中使用 =
(双向绑定),因此您不应在百分比属性值中使用 {{}}
。直接计算的值可以传递给用 ()
括号包裹的 percentage
属性。
虽然显示进度条的绑定百分比,您可以使用 ng-style
指令和 $ctrl.percentage
值,该值已传递给组件 bindings
。
HTML
<progress-bar percentage="{{(count / total)}}"></progress-bar>
指令模板
template: '<div class="progressBar">\
<div class="inner" ng-style="{ width: $ctrl.percentage+\'%\'}"></div>\
</div>',