繁体   English   中英

使用AngularJs指令更新输入值

[英]Using AngularJs directive to update input value

我正在尝试更新weatherApp输入字段

<input type="number" class="hidden-input" ng-model="updatedWeather.SurfaceWind.Gust" winds></input>

通过使用角度指令:

.directive('winds', windDirective);

function windDirective () {
return {
    restrict: 'A',
    require: 'ngModel',
    scope : { ngModel : '=?'},
    link: function (scope, element, attrs, ngModel) {
        element.bind('change', function () {
            console.log(ngModel);
            scope.$apply(setAnotherValue());
        });
        function setAnotherValue() {
            ngModel.$setViewValue("hello!");
            console.log(ngModel);
            ngModel.$render();
        }
    }
};

}

我在此之前声明了指令和控制器,并且一切似乎都在运行(成功登录到控制台)。 但是由于某种原因,每当我尝试更改输入字段时,该值默认为0,并且不会显示任何内容。 任何帮助,将不胜感激!

这是我对所需内容的理解:

演示: http//codepen.io/ozzieorca/pen/XXmJvV

<div ng-app="myApp">
  <wind>
    <div>
      <label>Wind Speed</label>
      <input type="number" ng-model="wind.speed">
    </div>
    <div>
      <label>Add Gust</label>
      <input type="number" ng-model="newGust">
      <button ng-click="wind.addGust(newGust)">Add</button>
    </div>
    Wind Speed: {{wind.speed}}<br>
    Gusts: {{wind.gusts | json}}<br>
    Total: {{wind.calculateTotal()}}
  </wind>
</div>
angular
  .module('myApp', []);

angular
  .module('myApp')
  .directive('wind', wind);

function wind() {
  return  {
    restrict: 'EA',
    controller: WindController,
    controllerAs: 'wind',
    bindToController: true
  };

  function WindController() {
    var vm = this;
    vm.speed = 0;
    vm.gusts = [];
    vm.addGust = addGust;
    vm.calculateTotal = calculateTotal;

    function addGust(val) {
      vm.gusts.push(val);
    }

    function calculateTotal(){
      return vm.speed + vm.gusts.reduce( (prev, curr) => prev + curr, 0 );
    }
  }
}

我可能还是有些困惑。 让我知道你的想法。 听起来您想要在同一输入中增加阵风和总显示。 也许您可以解释一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM