Angular's eval directive's parameters

Looking for a solution to manage parallax on mobile devices in my HTML template:

<div width-watcher>
    <div parallax-bg parallax-active="!(tablet || mobile)">
        ...
    </div>
</div>

The width-watcher includes boolean values for mobile, tablet, and screen. I need to evaluate the expression "!(tablet || mobile)" to pass it to the parallax-bg directive, disabling parallax on mobile devices.

I've attempted various methods in the parallax-bg:

  • Using scope.$eval(attr.parallaxActive) results in "undefined"
  • Accessing scope.parallaxActive directly with:
    • "&" yields a function that returns "undefined"
    • "=" also returns "undefined"
    • "@" provides "!(tablet || mobile)"

After exhausting my options, I'm seeking additional solutions as English is not my first language, potentially missing some answers on Google.

Below is the code snippet for my background-parallax directive:

.directive('parallaxBackground', function($window) {
return {
    transclude: true,
    template: '<div ng-transclude></div>',
    scope: {
        parallaxRatio: '@',
        parallaxOffset: '@',
    },
    link: function(scope, elem, attrs) {
        var scopeActive = scope.$eval(attrs.parallaxActive);
        var ...
        if(scopeActive){
            ...
        }
    }
};

Answer №1

Initially, you used the method scope.$eval(attr.parallaxActive), which is accurate, but it may not function properly if the attribute value is bound to your directive's scope.

For a working example, check out this JSFiddle.

angular.module('myApp').directive(function() {
  return {
    link: postLink,
    template: '<ng-transclude></ng-transclude>',
    transclude: true
  };

  function postLink(scope, iElement, iAttrs) {
    alert(scope.$eval(iAttrs.parallaxActive));
  };
}

Instead, I suggest converting your widthWatcher directive into a service using the factory strategy. This way, you can inject it into any controller, directive, filter, or other services and determine the screen type without depending on scope.

Here's a working example on JSFiddle.

angular.module('myApp', [])
  .factory('$widthWatcher', widthWatcherFactory)
  .directive('parallaxBg', parallaxBgDirective)
;

function widthWatcherFactory() {
  return {
    isMobile: isMobile,
    isScreen: isScreen,
    isTablet: isTablet
  };

  function getWidth() {
    return window.innerWidth || document.body.clientWidth;
  }

  function isMobile() {
    return getWidth() < 600;
  }

  function isScreen() {
    return getWidth() > 960;
  }

  function isTablet() {
    return !isMobile() && !isScreen();
  }
}

function parallaxBgDirective($widthWatcher) {
  return {
    link: postLink,
    template: '<ng-transclude></ng-transclude>',
    transclude: true
  };

  function postLink(scope, iElement, iAttrs) {
    alert($widthWatcher.isScreen());
  };
}

UPDATE

In response to the comment about values being undefined when the parallaxBg link function is called, I have made updates to the JSFiddle to demonstrate the order in which link functions are executed.

To comprehend what is happening, it is essential to understand how directives are compiled.

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

Is it possible to incorporate RequireJS in importing VueJS components?

I am currently working on a project that involves using both RequireJS and Vue components. One of my goals is to break down the Vue components into smaller pieces for better organization, and I want to be able to export these smaller components so they can ...

Missing table header in HTML causing table to not display correctly

I currently have an HTML table that consists of three columns and a varying number of rows, depending on the output from a database. var fields = ['a','b','c']; //variable from database var data = ['p', & ...

Using jQuery to arrange information from an API into a table

Currently, I am in the process of learning jQuery as it is a new concept for me. I have attempted to make a request to an example API and received an array of objects that need to be listed in a table. However, I am facing difficulty in sorting it within t ...

Algorithm using JavaScript to identify objects within an array

I am working with an array of objects that contain information about different projects. Each project has a unique ID and two arrays, one containing the IDs of projects that will happen before it, and another with the IDs of projects that will follow. Here ...

Implementing $timeout within ng-init to execute a function that showcases various shapes at 2-second intervals

I'm trying to use $timeout in Angular 1 to call a function every 2 seconds using ng-init. ng-init="$timeout(sc.displaySorted(), 2000)" The sc.displaySorted() function displays 100 sorted shapes on the DOM. It works fine with ng-init, but I'm st ...

How can Vuetify components be imported separately in the right way?

I’m currently getting acquainted with Vuetify and I’m finding it quite challenging to figure out how to import a specific component for use. My current version of Vuetify is 2.4.2 According to the documentation, they mentioned about the path to vueti ...

Having trouble with [Object Object] errors in your hybrid app using Javascript?

I'm currently developing a hybrid app using Nuxt JS, Cordova, and Cordova Native Storage (essentially localstorage). During the process of saving an object to native storage and retrieving it on page load within the mounted() method, I keep encounter ...

Having trouble getting ng-include to work while running my Angular app locally

I am in the process of developing a small Angular app. As part of this, I am utilizing ng-include to call simple partials like so: <div ng-include="'partials/footer.html'"> </div> However, when I try to load the page using live-serv ...

Enhancing live query functionality and providing a substitute for DOMNodeInserted specifically tailored for

I have searched multiple times on various platforms for a solution to my specific issue, but have not found one that fits my unique circumstances. My goal is to replace outdated code such as livequery and DOMNodeInserted. See examples below. I am current ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

Sending information to a singular Vue component file

Struggling to pass data to props and render different content in a component on each page? Want to display links, tech, feedback without deleting the component or rewriting code for individual pages? Existing methods not working for you? Unsure if what you ...

The WkWebView Message handler fails to return the value of the textbox initially, but successfully does so after pressing the button a second time

Having an HTML form embedded in a WKWebView in my Swift app poses a problem when trying to extract the textbox content using a message handler. The issue arises when pressing the Register button, which triggers a JavaScript function to retrieve the values ...

How can I make a page scroll to the center when clicking on a carousel?

My goal is to create a webpage where clicking on the carousel will center it on the page. A great example of this functionality can be seen on the Studio New Work website (). As I am still in the process of learning JQuery, I have not yet mastered all the ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

Monitoring vuex mutations and actions within a component: A step-by-step guide

Is there a way to detect and react whenever events occur across the page, such as animations starting or finishing, requests firing or failing? I want a component to be able to respond to these occurrences. It's simple to watch a getter by importing ...

When transitioning to the production environment, Nuxt.js fails to load images

I am currently working on developing a rather large app. Everything was running smoothly in the development environment without any errors. However, upon switching to the production environment, I started encountering numerous errors. Nuxt seems to be havi ...

Having trouble getting tagmanager.js to work on my JSF 2.2 form. Can anyone help me troubleshoot what is going wrong?

Struggling for hours to make tagmanager.js function on my JSF 2.2 page has left me perplexed. I was successful using jsp pages, but they are outdated now. Even though I can input the tags properly, they fail to reach my java bean upon form submission. Titl ...

My Angular project is experiencing issues with Socket.IO functionality

After successfully using a post method in my endpoint, I encountered an error when integrating it with socket io. The error pertained to a connection error and method not being found. Any help or source code provided would be greatly ap ...

Leverage the power of Vuex within your Nuxt application

I successfully obtained and displayed data using Nuxt's Fetch API, but now I'm looking to transition to using Vuex instead. store/index.js: import Axios from 'axios' export const getters = { isAuthenticated: (state) => { retu ...

Using Ajax script to transfer user information to a php file in order to refresh the modified row in a table

Recently, I created a table in PHP to display certain data. Here's how it looks: <?php echo '<table id="tableteste" class="table table-striped" width="100%">'; echo '<thead><tr>'; echo &apos ...