AngularJS - Struggling to retrieve value from ng-model in controller

Having trouble using Angular's ng-model to store and pass values with ng-click? If you're receiving undefined values in your current code, here's a possible solution. Check out the HTML snippet below:

HTML

<ion-content>
    <div class="list">
        <label class="item item-input">
            <textarea ng-model="feedback.comment"></textarea>
        </label>
    </div>
</ion-content>

<div class="tabs tabs-icon-left">
    <a class="tab-item" ng-click="submitFeedback(feedback)">
        <i class="icon ion-arrow-right-b"></i>
    </a>
</div>

JavaScript - Controller

.controller("FeedbackController", function($scope, $http, $localStorage){
    $http.get("https://api.example.com/data", { params: { access_token: $localStorage.token, fields: "id, location, picture", format: "json" }}).then(function(response) {
        $scope.userData = response.data;
        console.log(response.data);
    }, function(error) {
        alert("Error fetching user data");
        console.log(error);
    });

    $scope.submitFeedback = function(data){
        console.log(data);
    }
});

Routes

.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home')

$stateProvider
    .state('home', {
        url: '/',
        templateUrl: 'templates/home.html',
        controller: 'HomeController'
    })
    .state('profile', {
        url: '/profile',
        templateUrl: 'templates/profile.html',
        controller: 'ProfileController'
    })
    .state('dashboard', {
        url: '/dashboard',
        templateUrl: 'templates/dashboard.html',
        controller: 'DashboardController'
    })
    .state('feedback', {
        url: '/feedback',
        templateUrl: 'templates/feedback.html',
        controller: 'FeedbackController'
    })
})

Answer №1

It seems like the issue you're facing is related to scoping, as mentioned in the comments. The ion-content directive may be using an isolated scope, so setting a value inside it might not affect scopes outside of it.

To avoid such issues and more, consider using the controller as syntax.

Another reason could be that the feed object is not initialized. If feed is undefined, you cannot simply set feed.status = 'something'. Make sure to initialize feed first.

One approach is:

.state('post', {
        url: '/post',
        templateUrl: 'templates/post.html',
        controller: 'PostController',
        controllerAs: 'vm'
    })

In your controller:

.controller("PostController", function($http, $localStorage, $location){
    var vm = this;
    vm.feed = {}; //initialize feed object
    $http.get("https://graph.facebook.com/v2.2/me", { params: { access_token: $localStorage.accessToken, fields: "id, location, picture", format: "json" }}).then(function(result) {
        vm.profileData = result.data;
        console.log( result.data);
    }, function(error) {
        alert("There is a problem with your profile");
        console.log(error);
    });

    vm.post = function(data){
        console.log(data);
    }
});

In your template:

<div>
<ion-content>
    <div class="list">
        <label class="item item-input">
            <textarea ng-model="vm.feed.status"></textarea>
        </label>
    </div>
</ion-content>

<div class="tabs tabs-icon-left">
    <a class="tab-item" ng-click="vm.post(vm.feed)">
        <i class="icon ion-arrow-right-b"></i>
    </a>
</div>
</div>

Give it a try and let us know if it works!

Answer №2

It seems like your code will function correctly if you enclose it all within the ng-controller tag:

<div ng-controller="MyController">
    <!-- Add your HTML content here -->
</div>

You can view it in action on JSFiddle: http://jsfiddle.net/gmy6gd8z/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the execution duration on an HTML document

Recently, I created a loan calculator using Javascript and now I'm contemplating on incorporating the time taken for the code to execute into the results. My intention is to have the execution time displayed on my HTML page, but I am unsure of how to ...

Passing an object using Ionic Vue's router-link

Looking to send an object as a prop to another page using a router-link in Ionic-Vue. When clicking on the link I created, it looks like nothing is getting passed through. Here's the link I currently have: <router-link :to="{ name: 'mov ...

Issues of unfulfilled requirements in the recent npm (and node) updates

After updating npm and node to the latest versions, I am encountering the following errors and warnings: $ npm --version 2.4.1 $ node --version v0.10.36 $ npm install > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f895 ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...

Generate a new item using an existing one

I am seeking to extract the desired output from the provided input: Input Configuration: var inputParams = { 'inputDetails' :[ { 'field' : 'specificationName', 'value' : 'strong'}, { ...

Ionic is encountering a problem with module build, specifically an error related to the absence of a file or directory

Using Ionic has led to encountering the following error message: Runtime Error Uncaught (in promise): Error: Module build failed: Error: ENOENT: no such file or directory, open '/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/r ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

How can I wait for an onclick action to pause, loop, or continue inside of a loop?

The form's onsubmit function triggers a pop-up message asking the user if they want to proceed before submitting the form. This requires the onsubmit function to wait for the user's final input in order to fully execute the form. Here is the cod ...

Toggle button visibility in AngularJS based on checkbox selection

I'm currently utilizing ng-table to construct my table. I have a button positioned at the top of the table that is initially disabled. My goal is to enable this button only when any of the checkboxes are selected. The button should automatically disab ...

Retrieving an item from AsyncStorage produces a Promise

Insight I am attempting to utilize AsyncStorage to store a Token after a successful login. The token is obtained from the backend as a response once the user clicks on the Login button. Upon navigating to the ProfileScreen, I encounter difficulties in ret ...

"Troubleshooting: ngForm.controls returning undefined value in Angular application

Trying to test this HTML code in Angular: <form name="formCercarUsiari" #formCercarUsuari="ngForm" class="tab-content"> <input #inputNif class="form-control input-height" maxlength="100" type="text" placeholder="Indiqui NIF" name="nif" i18n-pla ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

Align the inline text at the center as if it were an inline-block element

Currently working on a design that appears deceptively simple, yet I'm encountering challenges in centering it while keeping the text aligned to the left. https://i.sstatic.net/qhf6p.png In an attempt to have the background span only the actual text ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...

Is there a way to prevent javascript from automatically inserting tags when selecting text?

If you want to view the Fiddle Here Essentially, it's a text-highlighting tool that works almost flawlessly. The problem arises when it encounters tags like <p> or <br> within the selection. The JavaScript code seems to automatically in ...

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

Injecting live data into an input field within a table using Angular 4

Trying to create a dynamic row table with input fields in all cells. The loaded data is static, and I'm facing issues adding more data in the view. However, the functionality to add and delete rows is working fine. I have experimented with ngModel and ...

How can I slow down the response time in Express Node?

I have set up a route that triggers an asynchronous function when the URL is accessed. This function will eventually return a value, which I want to use as the response for the get request. However, I am facing an issue with delaying the response until the ...