【问题标题】:How to defined a new variable in AngularJS component如何在 AngularJS 组件中定义一个新变量
【发布时间】:2016-11-13 16:35:09
【问题描述】:

我试图创建一个与进度条相对应的 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 以来,我很难有效地调试这段代码。

【问题讨论】:

    标签: javascript angularjs progress-bar components angularjs-components


    【解决方案1】:

    当您在组件中使用=(双向绑定)时,您不应该在百分比属性值中使用{{}}。直接计算的值可以传递给用()括号包裹的percentage属性。

    在显示进度条的绑定百分比时,您可以使用带有$ctrl.percentage 值的ng-style 指令,该值已传递给组件bindings

    HTML

    <progress-bar percentage="{{(count / total)}}"></progress-bar>
    

    指令模板

    template: '<div class="progressBar">\
            <div class="inner" ng-style="{ width: $ctrl.percentage+\'%\'}"></div>\
        </div>',
    

    JSFiddle Here

    【讨论】:

    • 组件的宽度永远不会改变,因为它只设置渲染的百分比,该值可以附加到一个公共服务以正确地动态处理它。
    • @Goliadkin 亲爱的先生,您检查过小提琴吗?这就是= 用于双向投标的方式,
    • @PankajParkar 谢谢!进度条没有移动,因此尽管您进行了修改,但它仍然无法正常工作:(我已经对其进行了编辑以正确设置宽度(缺少*100):jsfiddle.net/p8xqyhng/2 第二个问题,var self = this; 是用于?
    • @fef 哦,对不起,我错过了那部分。我用var self = this; 来减少将来this vs that 的问题。
    • @fef 也看看更新的小提琴.. 昨天我忘了在添加它之前保存小提琴
    猜你喜欢
    • 1970-01-01
    • 2021-03-02
    • 2015-06-07
    • 2014-11-02
    • 2022-11-23
    • 2016-09-09
    • 1970-01-01
    • 2015-03-17
    • 2011-09-27
    相关资源
    最近更新 更多