我试图使用角度js从输入调用文本

时间:2015-12-11 22:59:39

标签: javascript angularjs

我正在尝试使用Angular JS调用已添加到输入的文本,但是在我的控制台日志中,我一直未定义。

<div ng-controller="favouritesController" class="col-xs-12 favList">
  <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
  <ul>
  <li ng-repeat="weatherList in weatherLists" class="col-xs-12">
  <span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
  <div class="col-xs-12 col-sm-2">
    <button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
    <div class="col-xs-12">
      <input type="text" ng-model="serverip"/>
      <button ng-click="save(serverip)">Save</button>
    </div>
  </div>
</li>
</ul>
</div>

js code

myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
 $scope.save = function(){
  console.log($scope.serverip)
 }
})

2 个答案:

答案 0 :(得分:1)

您不需要将参数传递给save函数(并且您对save的定义不包括它)。 将按钮更改为:

      <button ng-click="save()">Save</button>

或者接受函数声明中的参数:

$scope.save = function(serverip){
 console.log(serverip)
}

答案 1 :(得分:0)

ng-repeat创建一个新范围,从上面的范围继承。您正在将serverip分配给此新创建的范围。因此,favouritesController上下文中的$ scope没有这个记录。你应该在你的保存函数中接受一个参数并记录下来(因为你正在传递这个函数的参数。)

编辑: 或者,作为替代方案......公开一个将由ng-repeat继承的财产:

控制器:

myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
 $scope.ip = { serverip:'' };
 $scope.save = function(){
  console.log($scope.ip.serverip)
 }
});

模板

<div ng-controller="favouritesController" class="col-xs-12 favList">
  <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
  <ul>
  <li ng-repeat="weatherList in weatherLists" class="col-xs-12">
  <span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
  <div class="col-xs-12 col-sm-2">
    <button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
    <div class="col-xs-12">
      <input type="text" ng-model="ip.serverip"/>
      <button ng-click="save()">Save</button>
    </div>
  </div>
</li>
</ul>
</div>