Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this:

<script>

myArray=<?php echo $array;?>;
app={
    myArray:myArray,
    myIndex:myArray.length-1,
    back:function(){this.myIndex--;console.log("You clicked back");},
    forward:function(){this.myIndex++}
}
</script>

Later on, you decide to integrate a UI using angularJS. You write the following code:

<div ng-app="myApp">
    <div ng-controller="AppCtrl">
        <div ng-repeat="value in myArray | slice:myIndex:myIndex+1">
            <div ng-cick="back()">Back</div>
            <div ng-bind="value"></div>
            <div ng-cick="forward()">Forward</div>
        </div>
    </div>
</div>

You also include the following JavaScript code:

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

myApp.filter('slice', function() {
  return function(arr, start, end) {
    return arr.slice(start, end);
  };
});

myApp.controller("AppCtrl",function($scope){
    $.extend($scope,app);
})

However, when you click the back button, the console logs "You clicked back" but the value does not change. Why is JQuery extend not working in this scenario and how can you fix this issue?

Answer №1

$.extend will work perfectly.. However, it may not be necessary.. Please refer to this for more information.

To resolve the issue... simply follow these steps:

  myApp.controller("AppCtrl",function($scope){
      $scope.app = app;
  })

and.

  <div ng-controller="AppCtrl">
    <div ng-repeat="value in app.myArray | slice:app.myIndex:app.myIndex+1">
        <button ng-click="app.back()">Back</button>
        <div>{{value}}</div>
        <button ng-click="app.forward()">Forward</button>
    </div>
  </div>

I hope this guides you in the right direction.

update

One alternative solution is to use the controller as syntax... so

myApp.controller("AppCtrl",function(){
    angular.extend(this,app);
})

and

  <div ng-controller="AppCtrl as app">
    <div ng-repeat="value in app.myArray | slice:app.myIndex:app.myIndex+1">
        <button ng-click="app.back()">Back</button>
        <div ng-bind="value"></div>
        <button ng-click="app.forward()">Forward</button>
    </div>
  </div>

In the first example $scope.app has context (because its the owner of forward, back etc that you mixed in).

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 best way to select a specific button to handle the onSubmit event in a React form with multiple buttons

Imagine having the following HTML structure: <div id="container"></div> <p>Output: <span id="output"></span></p> accompanied by this block of JS code: function otherAction(e) { document.getElementById('output& ...

Efficient Error Handling in Next.JS with Apollo GraphQL Client

Although the component successfully renders the error state, an uncaught exception is displayed in the console and a dialogue box appears in the browser. How can expected errors be handled to prevent this behavior? import { useMutation, gql } from "@a ...

A modern CSS solution for a fixed columns and header layout in a scrollable table

How can I create a table with minimal JavaScript using modern CSS? I am aiming to include the following features: Fixed column(s) (positioning and width) Scrollable in both X and Y axes Responsive in the X axis (for non-fixed width columns). https://i. ...

What is the correct way to use getServerSideProps?

Lately, I've been exploring the world of web development by creating a web app using NextJS. While I have some knowledge of the basics in this field, I found myself a bit lost when working with NextJS since I hadn't worked with React before. One ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...

Error message in my Angular project: Invalid Target Error

Out of nowhere, I encountered an invalid target error while running my Angular project with the command: npm start An unhandled exception occurred: Invalid target: {"project":"agmbs","target":"build","configur ...

Error: Angular Directive has an undefined scope

I have a specific issue with my directive, where I am trying to extract data from an xls file and pass it to a button through the scope. The problem arises when I am binding to the element change event in the link function and calling a function to parse ...

What are the various ways to apply unique padding styles to ng-repeat items?

Take a look at this image. I need to position my 6 boxes on the 6 vertical lines above the image. I am struggling with applying different padding styles to my ng-repeat directive. Although I tried using [ng-class], it doesn't seem to work as expected. ...

Hiding content and troubleshooting video playback problems in FancyBox

I'm facing an interesting issue. I've implemented FancyBox lightbox to showcase a "video" tag when users click on the image thumbnail, and it functions well with all varieties of HTML5 video. The challenge arises when testing in browsers older th ...

Discover how to initiate an ajax request from a tailored module when the page is loaded in ActiveCollab

When trying to initiate an AJAX call on the project brief page by adding a JavaScript file, I encountered some issues. My goal is to display additional information along with the existing project brief. I included a JavaScript file in a custom module and f ...

The initial item in a pagination/list is double-parsed on an AJAX website using Selenium 3.0.2, Firefox webdriver, and BeautifulSoup 4.5.1

For the past three days, I've been facing a frustrating issue with both Selenium and Bs4. While I suspect Selenium (or my code) to be the culprit. Like many others before me, I'm attempting to scrape data from this website: I'm moving from ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

Utilize Javascript to conceal images

On a regular basis, I utilize these flashcards. Recently, I have started using images as answers. However, I am facing an issue - I am unable to conceal the pictures. My preference is for the images to be hidden when the webpage loads. function myShowTe ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...

Controlling Formatting in ASP.NET

Feeling puzzled by a seemingly simple question with no clear solution in sight. We're attempting to transition an interface to an ASP.NET control that currently appears like this: <link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLa ...

Tips for activating a deactivated input field in ReactJS

I am trying to create a feature where my textfields are automatically disabled, but can be enabled for editing by clicking an 'Edit' button. Clicking the button again should disable the textfields and save any edits made. I have experimented with ...

The best practices for integrating Firebase with REST APIs

While searching for a tutorial on integrating REST APIs with Firebase, I came across numerous code snippets utilizing the curl method calls or other helper libraries. However, what I couldn't find were the basics - such as where to call these methods ...

Unlock the secrets of filtering a JSON array object with nested SQL Query-like precision using ES6 syntax for maximum efficiency

As someone new to ES6 syntax, I could use some assistance with this task. I have a JSON array structured like so: var data = [{ "recordid": 1, "recordidclass": "Parent Class", "relatedrecid": 2, "relatedrecclass": "Child Class2" }, { ...

Is it possible to navigate between jQuery EditInPlace fields using the Tab key?

Seeking advice on implementing tab functionality for a page with multiple jquery EditInPlace fields. The goal is to allow users to navigate between fields by pressing the tab key. Currently using the 'jquery-in-place-editor' plugin available at: ...