访问ng-model值

时间:2014-12-17 14:10:17

标签: angularjs

  <div ng-controller="NotesController as noteCtrl">

<div class="form-group">
  <input class="form-control" id="inputdefault" type="text" style="float: left;width: 90%;" ng-model="newNoteText" >
  <button class="btn btn-primary" ng-click='noteCtrl.addNewNote()' type="button" style="margin-left: 0.5%"><span class="glyphicon glyphicon-plus"></span>&nbsp;ADD</button>

</div>

============================================

    var app=angular.module('myApp',[]);
app.controller("NotesController",function(){
  this.allNotes=notes;
  this.note={};
  this.addNewNote=function(){
    alert(newNoteText);
  };

});

请告诉我如何访问控制器中的输入文本框值?

3 个答案:

答案 0 :(得分:0)

您甚至没有注入$ scope变量。你想要这样的东西:

app.controller('NotesController', function($scope) {
    $scope.allNotes=notes;
    $scope.note={};
    $scope.addNewNote = function(){
        alert($scope.newNoteText);
    };
});

无需在Angular中使用this

答案 1 :(得分:0)

您需要注入范围变量:

var app = angular.module('myApp', []);
app.controller("NotesController", function ($scope) {
    $scope.allNotes = $scope.notes;
    $scope.note = {};
    $scope.addNewNote = function () {
        console.log($scope.newNoteText);
    };
});

查看我的fiddle

答案 2 :(得分:0)

由于您使用的是控制器,因此无需注入$ scope。只需替换它:

 ng-model="newNoteText"

用这个:

ng-model="noteCtrl.newNoteText"

并在你的控制器中替换它:

alert(newNoteText);

用这个:

alert(this.newNoteText);