使用AngularJs指令更新输入值

时间:2015-12-11 17:16:52

标签: javascript angularjs

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

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

使用Angular Directive:

.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,并且不显示任何内容。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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 );
    }
  }
}

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