What steps are necessary to enable two-way binding in Angular using the latest controllerAs syntax and Object-Oriented Controllers?

Concerned about "scope soup" where too much functionality is added to the $scope, I am currently exploring Object-Oriented controllers, the new controllerAs syntax, and using EC5 style getter/setters in my controller. While this approach is effective, I am struggling to establish a two-way binding between my directive's scope and my controller's scope. I have created a codePen demo to illustrate the issue.

http://codepen.io/anon/pen/DlfxB?editors=101

I am anticipating the following code line to function as intended:

scope: { pants: '='},

Answer №1

If you are using version 1.3 rc of AngularJS, you have the option to utilize the bindToController option. This allows for the two-way bound scope variables to be directly linked to the controller. If not using this option, you would need to manually map the properties to the controller instance, which can be cumbersome. Alternatively, you can use the regular syntax without the controller for two-way binding properties. For example, you can do

'<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">'
with bindToController:true in the directive configuration.

bindToController
  • When an isolate scope is used for a component (see above) and controllerAs is used, bindToController will
  • allow a component's properties to be bound directly to the controller rather than the scope. Upon instantiation of the controller, the initial values of the isolate scope bindings are readily available.

(function(){
    
   var myApp = angular.module('plunker', []);

    var helloEC5 = function(){
      this.pants = "jeans";
    };
    helloEC5.prototype = {
        firstName: 'Seeya',
        lastName: 'Latir',
        get fullName() {
            return this.firstName + ' ' + this.lastName;
        },
        set fullName (name) {
            var words = name.toString().split(' ');
            this.firstName = words[0] || '';
            this.lastName = words[1] || '';
        }
    };
    myApp.controller('HelloEC5', helloEC5);
    myApp.directive('myDirective', function () {
        return {
          scope: { pants: '='},
          controllerAs: 'my',
          controller: function(){},
          bindToController:true,
          template: '<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">'
        }
    });
 })();
   <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dece3eaf8e1ecffa3e7fecdbca3bea3bda0ffeea3bc">[email protected]</a>" data-semver="1.3.0-rc.1" src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script>

  <div ng-app="plunker">
    <div ng-controller="HelloEC5 as EC5">
      <p>HelloEC5 says my name is: {{EC5.fullName}} wearing {{EC5.pants}}!</p>
      <label>Pants:</label>
      <input ng-model="EC5.pants" type="text" />
      <label>FirstName:</label>
      <input ng-model="EC5.firstName" type="text" />
      <div my-directive="" pants="EC5.pants"></div>
      <hr />
      <label>Setting HelloEC5.fullName:</label>
      <input ng-model="EC5.fullName" />
    </div>
  </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

Incorporate a `fresh Audio` element into my redux repository

I'm attempting to include a new Audio element in my redux store. This is how my reducer appears: export const songsReducer = (state = {}, action) => { switch (action.type) { case "PLAY_SONG": return { ...state ...

Enhancing the efficiency of a Puppeteer web scraping operation

app.get("/home", async (req, res) => { try { const browser = await puppeteer.launch(); const page = await browser.newPage(); const pageNumber = req.query.page || 1; await page.goto(`https://gogoanimehd.io/?page=${pageNumber ...

Automatically redirect to a different page upon clicking the jquery popup button

I integrated a jQuery popup feature on my website to display messages. Now, I am looking to implement a redirect to another page when the user clicks a button within the jQuery popup. However, I am unsure of how to achieve this. <script type="text/ja ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

What could be causing my dropdown links to malfunction on the desktop version?

I've been developing a responsive website and encountering an issue. In desktop view, the icon on the far right (known as "dropdown-btn") is supposed to activate a dropdown menu with contact links. However, for some unknown reason, the links are not f ...

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

Having trouble retrieving a value within the jQuery.ajax success function

I need to implement jQuery Validator in order to validate if a user's desired username is available during the sign-up process. The PHP script untaken.php is responsible for checking this, returning either ok if the username is free or taken if it is ...

Troubleshooting Issues with jQuery Accordion Buttons

I have a nearly complete accordion that just needs some adjustments. HTML CODE: <footer> <div> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> ...

Verify the dialog box return with a text input box

I am trying to implement a confirmation dialog box for when a user wants to delete their account. This dialog box requires the user to enter their password in a textbox. However, I am struggling with catching the postback event and executing the relevant m ...

"Transforming JSON data into a format compatible with Highcharts in PHP: A step-by-step

Currently facing an issue with converting the given array format into a Highcharts compatible JSON to create a line chart. Although everything else is functioning correctly, I am struggling with this specific conversion task. { name: [ 1000, ...

What is the solution to incorporating a scrollbar in a popup when I increase the zoom level?

When trying to add a scrollbar to the popup, I am facing an issue where the scrollbar does not appear when zoomed in to 75% or 100%. It works fine for fit screen but not on zoom. Can anyone help me identify what is wrong with my code and suggest how to han ...

Utilizing URL encoding instead of JSON when using Postman

I've hit a roadblock - I've spent almost the whole day trying to solve this issue. We are working on integrating csrf security into our website, which is built with play framework 2.5.9 and angularjs 1.x. I've added the csrf components and t ...

Transform the year into the Buddhist calendar system

I recently started learning AngularJS and have a question. I am currently using Date.now() to get the current time, but I would like to display the year in Buddhist format. I came across a code snippet in this topic -> How to make a ticking clock (time) ...

Select2 using AJAX: chosen option disappears upon receiving AJAX response

Despite going through numerous questions and answers, the issue persists. Here is an excerpt of the code in question: <div class="col-md-2"> <label for="wh_location">{{ __('reports.warehouse_movement.location') ...

What is the most effective method for displaying two external web pages next to each other?

Looking for a solution to display an English Wikipedia article on the left side of the page alongside its Spanish version on the right side. Wondering if it's possible using HTML, JavaScript, AJAX, etc. I am aware that I could use iframes, but I woul ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

Refreshing the entire page upon modifying a single state

I am currently in the process of constructing a page that includes numerous Charts, and I am utilizing a Material UI menu to switch between graphs. Each time I click on a new MenuItem, it alters my state and presents a new array of components. The pr ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

How can one determine the completion of a chunked download request in Angular's HTTP client?

Currently, I am utilizing angular's HttpClient to retrieve an arraybuffer. The server is transmitting the data along with the following headers: *To avoid any confusion, the download route essentially retrieves a chunk file stored in the cloud. Howev ...

What could be causing the header of the datatable to be out of alignment with the rest of

I'm facing an issue with my datatable where the header is misaligned with the content. Can someone please assist me in adjusting the header and content so that they are parallel? It doesn't look right at the moment. <div style="margin-top:1 ...