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

A guide on replacing certain characters with spaces using AngularJS

I'm struggling with replacing special characters in a name (Inka -Tiitto-s-Camp-Aero-Gravity-Milan-9) with hyphens (-) due to an error message that says, "The URI you submitted has disallowed characters." Additionally, the name appears as (Inka Tiitto ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

Personalized Svelte interface Slider tag

I am trying to customize the label of a smui/slider in a tick marks and discrete slider. While I found instructions on how to do this using material web components at https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc- ...

I'm facing an issue where the ui.router is not functioning properly. I am unsure

I am currently trying to replace ngRoute with ui-router in order to utilize multiple views. Within my template file, I have the following code: <div ui-view></div> In my application file, I have the following configuration: angular.module(&a ...

A guide on activating dropdown buttons individually using AngularJS (Cascading dropdowns)

When it comes to cascading dropdowns (for example: with 3 dropdowns), the challenge is to disable the 2nd and 3rd dropdown initially. Only when a user selects an option in the 1st dropdown, should the 2nd dropdown be enabled. Similarly, once an option is s ...

How can I retrieve properties from a superclass in Typescript/Phaser?

Within my parent class, I have inherited from Phaser.GameObjects.Container. This parent class contains a property called InformationPanel which is of a custom class. The container also has multiple children of type Container. I am attempting to access the ...

Display temporary image until real image loads within ng-repeat angularjs

I am looking to display a placeholder image while the actual image is being loaded. I have tried using the ng-image-appear plugin. The issue I'm facing is that the placeholder image does not appear for img elements inside ng-repeat, although it works ...

Unable to navigate beyond the boundaries of an app

I am currently facing an issue with my authentication service where it redirects to the identity server in case of certain errors. I attempted to achieve this using window.location.href = environment.authCodeFlowIssuer;, however, an error occurred: Ref ...

Using SVG graphics as data labels in a HighChart stacked column chart

I am attempting to generate a stacked column chart in Highcharts with SVG images as x-axis labels, similar to the image displayed here: https://i.stack.imgur.com/y5gL1.png I have managed to achieve this with individual data points per label (non-stacked ...

Is there a way to incorporate the use of quotation marks within the ng-bind directive in AngularJS?

Is there a way to insert phoneNo["phoneno"] into an HTML input using the ng-bind directive in Angular? While {{phoneNo["phoneno"]}} can display the data, it results in a syntax error when I try to put it like this: <input class="form-control" type="t ...

Retrieving JSON data without using Jquery's Ajax function

I was wondering if there is any way to retrieve the results of a jQuery AJAX call and store them in a traditional variable for use as a function. Here's an example: function getPoints(){ //An array of JSON objects var Points; ...

Transform form data from square notation to dot notation using jQuery

During my ajax operations, I noticed that the data being sent is in JSON format. However, when checking Chrome tools -> network XHR, I observed that the form parameters are displayed within square brackets. Example: source[title]:xxxxxxxxxxxx source[thu ...

Is there a method to accurately detect the rendering of individual elements within a React Component, rather than the entire component itself?

While it's known that Components rendering can be detected through React's Developer Tool, I came across other methods in this source. However, what I'm specifically interested in is detecting the rendering of individual elements within a Co ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Error: The method `push` within the `useHistory` function is causing an issue and is currently undefined

Whenever the home button is clicked, I need it to redirect to the homepage '/ '. However, I keep encountering this error. Any suggestions on what steps I should take to resolve this? : import { Route, useHistory } from 'react-router-dom/cjs/ ...

"Unlocking the Power of Social Interaction with Vue.js

I've successfully integrated a Facebook Login module in my project and it's working well. However, I'm facing difficulties when trying to link the response data with an input field. Can someone guide me on how to achieve this? I'm still ...

IE encounters issues making Ajax calls when transitioning from secure HTTPS requests to insecure HTTP requests

I am currently facing an issue with my ajax CORS request. It is functioning perfectly on all browsers except for Internet Explorer. In IE, the request doesn't even attempt to go through and fails instantly without any error messages appearing in the c ...

What is the best way to instantiate a dynamic object within a literal?

I am dealing with an object that contains multiple fields, mainly consisting of constant string values. However, I also need to incorporate a variable that is determined by the current state. const {order} = this.state; myObject={{ fieldA: 2, fiel ...

Looping through a JSON object to create a table showcasing public holidays

Currently, I am working on creating a table that lists all the public holidays. The table comprises rows with holiday names on the left and dates on the right. Unfortunately, the table only displays data from the final array of the JSON object, whereas I ...

What is the ideal way to utilize Vue within the framework of multiple pages?

When using the default Vue CLI setup, Vue is loaded from the index.html page. To work with Vue and dynamic content on the page, everything is typically handled in the App.vue file. But what if you want to make significant layout changes to the page? How d ...