Utilizing ng-model and ng-repeat in a custom directive

Having trouble with a directive I'm building. I want to define options within the directive, but set a default option in my controller. The rendering looks good, but the default option isn't being selected. Any suggestions? Check out the Plunkr

    angular.module('app', [])
  .controller('Ctrl', function ($scope) {
    $scope.defaultSearchRange = 3;  
  })
  .directive('dateRange', function () {
    return {
      restrict: 'A',
      scope: {
        searchRange: '='
      },
      replace: true,
      template: '<div><select ng-model="searchRange"><option ng-repeat="option in options" value="{{option.value}}">{{option.name}}</option></select></div>',
      controller: function ($scope) {
        $scope.options = [
            { name: '',             value: 0 },
            { name: 'Today',        value: 1 },
            { name: 'Yesterday',    value: 2 },
            { name: 'Last 7 Days',  value: 3 },
            { name: 'Last 30 Days', value: 4 },
            { name: 'Month to Date',value: 5 },
            { name: 'Year to Date', value: 6 }
        ]
      }
    }
  })

Answer №1

To set the default value, consider using ng-options instead of ng-repeat. The track by variation allows you to select a value in the same "object format". Check out this working plunker here.

Here's how you can modify the code:

angular.module('app', [])
  .controller('Ctrl', function ($scope) {
    $scope.defaultSearchRange = 3;
  })
  .directive('dateRange', function () {
    return {
      restrict: 'A',
      scope: {
        searchRange: '='
      },
      replace: true,
      template: '<div><select ng-model="selected" ng-options="o.name for o in options track by o.value"></select></div>',
      link: function (scope) {

        scope.selected = { value: scope.searchRange };

        scope.$watch('selected', function(selected) {

          scope.searchRange = selected.value;
        });

        scope.options = [
            { name: '',             value: 0 },
            { name: 'Today',        value: 1 },
            { name: 'Yesterday',    value: 2 },
            { name: 'Last 7 Days',  value: 3 },
            { name: 'Last 30 Days', value: 4 },
            { name: 'Month to Date',value: 5 },
            { name: 'Year to Date', value: 6 }
        ];
      }
    }
  })

Please note that the above code introduces a new directive scope property selected. If the controller passes an object instead of just the number value, this step would not be necessary. Since the value is mapped, we must $watch and then map the selected value back out.

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

Steps to fix ESlint warning: Avoid using assignment in return Statement (no-return-assign)

In my React application, I am utilizing the package found at https://github.com/appleboy/react-recaptcha to create a Recaptcha component. Below is an image of what the component looks like, along with an eslint warning: https://i.sstatic.net/ZleMK.png Th ...

React, handling various router navigations

I have set up a BrowserRouter to serve /, /login, and /logout on my website. Once logged in, users can access an app with a consistent navbar on every page and dynamic content that holds data/functionality within the "Main" template component, which utiliz ...

What is the best way to unselect the "all" selector if one of the inputs is no longer selected?

I am facing an issue with a search filter functionality. When all filters are selected and then deselected individually or together, the "all" button remains selected. I need help in ensuring that when any filter is deselected, the "all" button also gets d ...

form for submitting multiple data via Ajax

I am working with two forms (request and feedback) where I need to use jQuery Ajax to send the data. When a user submits a request, the subject line will display "Request". If they submit feedback, the subject line will display "Feedback". Here is my cur ...

Updating ng-model does not trigger a refresh in AngularJS $scope

Looking at the html snippet below <input id="zoom" name="zoom" style="width:100px" type="text" ng-model="user.zoomlvl"> Executing the code block below updates the input field above google.maps.event.addListener(map, 'zoom_changed', funct ...

In Angular-Cli, the variables @Input and @Output are consistently null until they are assigned

Individuals' internal values are printed without any problems, but those obtained using @Input or @Output are not being displayed. child.component.ts @Component({ selector: 'app-form-input', templateUrl: './form-input.component.ht ...

Can you explain the correct folder configuration for a SpringBoot project that incorporates static files?

I'm having trouble figuring out why my SpringBoot web application isn't displaying in the browser. Here's what my debug log is showing: 2017-08-04 14:54:24.760 DEBUG 23863 --- [tp1027569178-15] o.s.w.servlet.view.InternalResourceView : For ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

There was a problem with the WebSocket handshake: the response header value for 'Sec-WebSocket-Protocol' did not match any of the values sent

I've encountered an issue with my React project that involves streaming live video through a WebSocket. Whenever the camera firmware is updated, I face an error in establishing the WebSocket connection. Here's how I initiate the WebSocket: wsRe ...

What could be the reason for the view/Vue.js dev tools not updating with the new data after pushing an item into a data array?

Despite pushing data into an array, the view and Vue dev tools do not update. Why is this happening? Even after clearing the browser cache, the issue persists. myData = [ [ { test: true } ] ] methods: { addDataItem() { ...

Issue with AngularJs Grid: Code does not function properly when placed within an event listener

Check out this code snippet: Functional version - Grid is displayed upon page load. <html ng-app="myApp"> <head lang="en"> <meta charset="utf-8"> <title>A Simple ngGrid Example</title> <link href="http://local ...

Enable AngularJS to automatically redirect to the login page when a user is not authenticated,

EDIT: I need to mention that my experience with AngularJs is only a week, so if you have any suggestions unrelated to the question itself, please feel free to share them in the comments section. Alright, here's the situation. I have authentication Co ...

Is there a way to integrate the distanceTo function from Leaflet into my own custom library that I am planning to develop?

I am currently incorporating leaflet into my project and I have encountered the distanceTo method which calculates the distance between two coordinates. My goal is to create a separate JS file with a function named getDistance() where I can house the logic ...

Change the height of textarea dynamically using jQuery

I am trying to create a comment box similar to Facebook's, where it resizes as text fills it using Expanding Text Areas Made Elegant This is how my view looks: <div class='expandingArea'> <pre><span></span></ ...

Improved Ecommerce Tracking with Google Tag Manager for an Angular JS Website

I am working with a client who has a website built entirely on Angular JS and we have implemented enhanced ecommerce tagging for them through GTM. One of the challenges we are facing is that on an Angular JS site, the data layer does not clear and refresh ...

Troubleshooting: Unable to delete data using $http in AngularJS

When using the $http service in Angular JS to call an API for deleting a message, I am receiving a successful response but the value is not actually being deleted. Interestingly, when I directly access the same API in my browser, the message gets deleted s ...

What are the steps for implementing responsive design animation in my particular scenario?

Can someone please help me with a strange bug in Chrome? I am trying to create a responsive design for my app. The width of the 'item' element should change based on the browser's width. It works fine when the page first loads in Chrome, b ...

Plunker is having trouble locating the angularfire simpleLogin feature

Utilizing Plunker to demonstrate some Angular features, I encountered a frustrating bug displaying the message: failed to instantiate module fireApp due to: [$injector:modulerr] Failed to instantiate module simpleLogin due to: [$injector:nomod] Module &apo ...

What is the best way to display or conceal buttons when the textarea is in focus or out of focus, while still allowing them

Seeking help to include two buttons beneath the input box. One button is for saving the input in the textarea, while the other is for aborting. The buttons should only be visible when the input field is focused. An issue I am facing is that clicking on ...

Trouble Arising in Showing the "X" Symbol upon Initial Click in Tic-Tac-Toe Match

Description: I'm currently developing a tic-tac-toe game, and I've run into an interesting issue. When I click on any box for the first time, the "X" symbol doesn't show up. However, it works fine after the initial click. Problem Details: ...