Modify the array dynamically within the Factory

I am currently working on a simple app where I want to display embed videos with the click of a button. It was quite challenging for me to dynamically bind my embed players, but I managed to do it successfully.

I created a factory that contains my data in an array form.

These data generate a list of buttons, and when I click on one of these buttons, I want the corresponding player to be displayed. To achieve this, I need to toggle the 'tv' value of the previously displayed video and toggle the one I just clicked.

Controller :

'use strict';
angular.module('myApp')
   .controller('MyAppCtrl', function ($scope, datas) {
     $scope.awesomeThings = ['HTML5 Boilerplate', 'AngularJS', 'Karma'];
     $scope.lives = datas.getLives();
 });

Factory :

'use strict';
angular.module('myApp')
  .factory('datas', function () {
    var factory = {};
    var lives = [
      {id:'1', title:'title1', tv: 'false', code:'code1'},
      {id:'2', title:'title2', tv: 'true', code:'code2'}
    ];
    factory.getLives = function () {
      return lives;
    };    
    return factory;
});

Directive for the embed player :

'use strict';
angular.module('myApp')
  .directive('dmcloud', function($sce) {
    return {
      restrict: 'EA',
      replace: true,
      scope: { code:'=' },
      template: '<iframe width="512" height="288" frameborder="0" scrolling="no" ng-src="{{url}}"></iframe>',
      link: function (scope) {
        scope.$watch('code', function (newVal) {
          if (newVal) {
            scope.url = $sce.trustAsResourceUrl('http://api.dmcloud.net/player/embed/' + newVal);
          }
        });
      }
    };
});
 

And finally, my view:

<ul>
  <li ng-repeat="live in lives">
    <input type="submit" ng-click="lives.toogleLive()" value="{{live.title}}">
  </li>
</ul> 

<h2>TV : </h2>

<div ng-repeat="live in lives | filter:tv = true">
  <dmcloud code="live.code"></dmcloud>
</div>

I am having trouble finding a clean way to change the appropriate 'tv' value. I am not sure where to place my 'toggleLive()' function. If you have any ideas, I would really appreciate your input. Thank you!

Answer №1

Take a look at this example: http://example.com Instead of using <iframe>, I decided to use <div>.

Answer №2

It seems like your directive is designed to handle changes in the code attribute. So, how about incorporating an activeTv property to keep track of the currently selected live TV program?

<ul>
<li ng-repeat="live in lives">
<input type="submit" ng-click="activeTv = live" value="{{live.title}}">
</li>
</ul> 

<h2>TV : </h2>

<div>
<dmcloud code="activeTv.code"></dmcloud>
</div>

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

The React.js .map function encountered an error while trying to map the results from Firebase

As a newcomer to the realm of React and Firebase, I find myself struggling with arrays and objects. It seems like the way my data is formatted or typed does not play well with the .map method. Despite scouring Stack Overflow for answers, none of the soluti ...

The AbortController feature does not initiate the cancellation of an axios.get request

Currently, I'm experimenting with utilizing AbortController to cancel an API call. The axios library is being used for this particular call. Before integrating it into my project, I decided to test the cancellation procedure with a simple call: const ...

Storing the usernames of users through local storage is essential for data preservation

My instructor mentioned a unique way to store user names using "localstorage" and arrays in JavaScript. This method ensures that the names are saved even if the page is reloaded. Here is the code snippet for achieving this functionality: html: <!doctyp ...

What is the rationale behind assigning a random value to the `(keyup)` event in order to update template local variables in Angular2?

To update #box in <p>, I need to give a random value to the (keyup) attribute. Here's an example: <!-- The value on the right of equality sign for (keyup) doesn't matter --> <input #box (keyup)="some_random_value" placeholder ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

Tips for adding additional rows or cells to a table with jQuery

Similar Questions: How to Add Table Rows with jQuery Adding Rows Dynamically using jQuery. I am currently working with a table that contains one row and five editable cells for user input. My goal is to implement an "Add Row" feature using jQuery ...

Removing duplicate entries from a dropdown menu can be achieved by implementing

As a newcomer to the world of PHP PDO, I've learned that the database connection should be in a separate PHP file. However, after spending an entire day trying different things, I'm still facing issues. I suspect that the duplicate entries are a ...

Tips for accessing $parent of ng-repeat from ng-include

In my code, I have a nested ng-repeat structure with an ng-include inside the inner ng-repeat. I am trying to access the outer ng-repeat using $parent within the ng-include. Here is an example of what I am working on: index.html <div ng-repeat="popula ...

What is the best way to distinguish a particular item in a <select> element and include a delete button for each row using jQuery?

1.) I've set up a nested table and now I want to ensure that when the 'Delete' button within the child table is clicked, its corresponding row gets deleted. 2.) I have a <select> tag. The issue is how can I implement validation to che ...

Only show the directive methods when using "ng-if"

I am facing an issue with the Opentoke Library directive, particularly when I use the ng-if. The reason for implementing the ng-if is that WebRTC is not supported on IOS devices, so it displays an alert after the DOM has loaded. <div class="opentok" ng ...

Is Vue js converting nested objects into strings before returning them?

There is an object in my code var user = { name:"test", number:"9666-0503", details:{ test:"cannot_access_this", second_field:"nope_no_go" } } A call to a Vue JS action is being made [TYPES.FETCH_USER]({ ...

Disable or set input text to read-only in Internet Explorer 9 and earlier versions using JavaScript or jQuery

Can anyone offer any suggestions on how to accomplish this task? I attempted using JavaScript with the code below, but it did not yield the desired results. element.readOnly="true"; element.readonly="readonly"; element.disabled="disabled"; I also tried ...

Tips for assigning an event to a variable in JavaScript

Here is my javascript code snippet: function drag(ev){ var x= ev.dataTransfer.setData("Text",ev.target.id); } I am trying to pass a variable within this event so that I can perform a specific action. However, the current implementation is not worki ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

Angular-jasmine: conducting tests on a component that utilizes timeout to render the DOM

Within my custom directive, I have implemented the following functionality: link: function (scope, element) { var editor = CKEDITOR.inline(element.find('div[contenteditable]')[0], {} To ensure that the directive is properly linked and that ...

The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event ...

VueJS is unable to identify the variable enclosed within the curly braces

I recently started learning VueJS and I've hit a roadblock. My goal is to display a variable, but for some reason, instead of seeing the product name, all I get is {{product}} Here's the HTML code I'm using: <!DOCTYPE html> <html l ...

Testing the functionality of an Express.js application through unit testing

I'm currently working on adding unit tests for a module where I need to ensure that app.use is called with / and the appropriate handler this.express.static('www/html'), as well as verifying that app.listen is being called with the correct p ...

Redirect to a new URL using $routeProvider's resolve feature

Currently, I am in the process of developing an application that includes the following endpoint: .when('/service/:id?', { templateUrl: 'views/service.html', controller: 'ServiceCtrl', resolve: { service: fu ...