Benedict Lewis
Benedict Lewis

Reputation: 2813

Pass input value to controller on enter or button click

I'm trying to get started learning AngularJS for an Ionic app I'm working on, and I'm having a little trouble understanding AngularJS having had most previous experience on jQuery which focuses on DOM manipulation rather than frameworking.

If I have the following markup:

<label class="item-input-wrapper">
  <i class="icon ion-ios7-chatbubble placeholder-icon"></i>
  <input type="text" placeholder="Send a message...">
</label>
<button class="button button-clear button-positive">
  Send
</button>

How can I pass the value of the input on to the controller when enter or send is clicked? I'm working on a chat app, so I believe that a model approach is needed so that the message thread can be automatically updated but other than that I have no idea.

Could someone help me out or at least point me in the right direction?

Upvotes: 6

Views: 30898

Answers (2)

Umayr
Umayr

Reputation: 933

There are several ways to pass value to your controller. Here is the simplest example. As Justin said, you should look into angular basics.

HTML:

<div ng-controller="MyCtrl">
     <input type="text" ng-model="foo" placeholder="Enter something" />
     <input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />
</div>

JS:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.foo = null;
    $scope.doSomething = function () {
        alert("Hello, " + $scope.foo);
    }
}

Here is the working fiddle

And I would recommend you to go through this post.

Upvotes: 9

justin
justin

Reputation: 13

The following markup you posted is the view. What you'll need to do is write a separate JS script called a controller that gets linked to the view. Look into basic Angular tutorials on how to do that and mainly look into how $scope works in Angular.

Your controller will have a function...say:

$scope.foo = function(input) { alert(input); };

From the view, you can pass a value onto the controller with Angular functions such as ng-click.

<a ng-click="foo('this string will be passed in as the text of the alert')">click me</a>

Upvotes: -1

Related Questions