Utilizing the ng-init directive to initialize code based on a JSON object

I am attempting to connect the value of ng-init to an input from a JSON object.

However, I am receiving a "Syntax Error: Token" message. Can someone help me identify where I am making a mistake?

$scope.obj = { init: 'obj.value = obj.value || 20' };

Plnkr : http://plnkr.co/edit/nmaxLvbqijXPBKoaQTUQ?p=preview

Answer №1

Consider using ng-required in place of ng-init

<form name="myformname">
  <input type="text" name="myinputname" ng-model="data.value" ng-required="{{data.init}}" /> 
</form>

Hopefully this suggestion is beneficial to you :)

Answer №2

Let's imagine 'begin' as a function that updates the value of the object.

$scope.obj = { 
    begin: function(){
          $scope.obj.value = $scope.obj.value || 20;
         } 
};

<input type="text" name="someinputname" ng-model="obj.value" ng-init="obj.begin()" /> 

Take a look at the Plunker

Answer №3

Here is a code snippet you can experiment with:

HTML

<input type="text" name="newinputname" ng-model="newObj.value" ng-init="initializeNewObj()" /> 

JavaScript

 $scope.newObj = {
    value: null
 };

 $scope.initializeNewObj = function() {
     $scope.newObj = { 
        initialized:  {
          value:  $scope.newObj.value | 20
        }
     };

   $scope.newObj = $scope.newObj.initialized;

 }

Answer №4

This method can achieve the desired result:

ng-init="$eval(obj.init)"

Check out the PLUNK here

ng-init essentially performs this action: scope.$eval(attrs.ngInit), meaning that the provided expression will be executed in this manner:

scope.$eval('$eval(obj.init)')

This will execute the expression stored in the variable obj.init.

Simply removing the curly brackets, as some have suggested, will not have the desired effect because it would result in the following function call:

scope.$eval('obj.init')

This would only return the value of obj.init and not actually execute it!

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

What is the method for utilizing a filter to extract the specific value from the elements within an array of double objects?

I am facing an issue with my code where I have an array called pick containing objects and another object named diaryItem. My goal is to extract only the object with the name 'wormColor' from the diaryItem object. Unfortunately, when I tried run ...

Performing ajax requests with nested ajax calls within a loop

I'm facing a particular issue. My code structure involves nested/foreach loops with ajax calls like below: var children = []; $.fn.ajaxHelper.loadAjax({ url: someUrlReturningJsonOfChildren, cache: true, callback: function(options) { ...

Efficiently sending a cookie with an Axios POST Request

My request is not receiving a cookie even after trying various solutions like withCredentials. I have pasted the most recent code here, can anyone spot what might be missing? var cookie_for_data = "token=test"; var host = "http://localh ...

Steps for displaying only one collapse at a time using either Bootstrap 3 or Bootstrap 4

As I work on constructing a website from the ground up using Bootstrap 4, I have encountered a roadblock that may be simple for an experienced Bootstrap developer. While I was able to find a solution involving raw Javascript code to collapse one element at ...

Issues encountered transferring data using wp_localize_script

I need help passing PHP data to a JavaScript script in my project. To achieve this, I am utilizing the wp_localize_script function. wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js'); wp_register_script(&apos ...

Troubleshooting a pair of .factory errors in AngularJS and Ionic

I am facing an issue with two .factory functions, where the second one throws an error. It seems like there is a restriction on having multiple .factory functions. Any assistance would be greatly appreciated. Thank you .factory('RawData', func ...

What issue is being encountered with this JavaScript generated by PHP?

PHP on the host generates JavaScript code that results in an error stating: missing ; before statement The generated JavaScript code looks like this: try{ obj = document.getElementById('subcat'); }catch(e){} try{ obj.innerHTML = ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

``Error: GraphQL server unable to initiate due to a failure in the module.exports

While learning GraphQL, I encountered an error when attempting to start a server. const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } ...

Node.js is receiving an empty body from Postman when using form-data in the request

Even though I've searched extensively, I still have not found a solution to my specific issue despite it being asked before. const express = require("express"); require("dotenv").config({ path: ".env", }); const PORT = ...

Execute Function on Double-Click with Flot.js

Is there a way to run a function when the mouse double-clicks while using flot? Currently, I am only able to trap the single click with the following code: $(graph).bind('plotclick', function(event, pos, item) { if (item) { .... ...

Steps for implementing a datepicker in a dynamically generated element

Snippet of jQuery code that adds an element to a container $(container).append( '<label class="control-label col-md-3">Join Duration</label>' + '<div class="col-md-4">' + '<input type="text" name="join_dura ...

Testing the equality of nested arrays: A step-by-step guide

My maze generator creates walls for each "cell", resulting in duplicate walls - such as the left wall of one cell being identical to the right wall of the adjacent cell. I have managed to convert the maze data into a different program where it is stored in ...

Arranging a JSON array based on the numerical value within an object

I am interested in sorting an array from a json file based on distances calculated using the haversine library. The purpose is to find geolocations near a specified value and display the closest results first. function map(position){ var obj, ...

Troubleshooting 404 errors with Cordova, AngularJS, and Node.js (Express) when using $http with

I'm currently testing in an Android environment using Cordova, AngularJS, and Node.js (Express). I'm attempting to retrieve some data using $http(), but consistently encountering a 404 error message (as seen in the alert below). Here's the ...

The dilemma of selecting objects in Three.js

Currently, I am developing a small web application that utilizes three.js. However, I have encountered an issue: I created a prototype with my three.js content and everything functions correctly (the canvas size in the prototype matches the browser window ...

Which is better for validation in Angular - $viewValue or $modelValue?

Being new to Angular, I am seeking validation on my form handling technique. Specifically, I want to notify the user with an appropriate message if they input more than 100 characters in a field. I am currently utilizing $viewValue for this purpose. Would ...

The function FileReader() is not functioning properly within a Vue computed property

I'm attempting to display a set of image thumbnails by dragging images onto the screen. Here is an example of my data structure: data() { return { files: [Image1, Image2, Image3] } } ...where each Image is in a blob format. Below is my co ...

The output of the incorrect .bind() example is not as

I recently came across the .bind() method while learning JavaScript. The example I found on MDN here was quite helpful, but I decided to add some console.log() statements for better understanding. this.x = 9; // Here 'this' refers to the glob ...

Conflicting node module versions arise during the installation of modules for electron

I'm currently developing an Electron application that interfaces with a serial port to read data. While I have experience with C++, I am relatively new to web technologies, although I do have some knowledge of JavaScript. After pulling the quick-star ...