Can an element be dynamically bound and unbound upon clicking a button in AngularJS?

After creating a display text and an input field, I bound them together using ng-model in the code below:

HTML

<div ng-app ng-controller="test">
    <div ng-bind="content"></div>
    <input id="txtElem" type="text" ng-model="content">
        <button ng-click="stopBinding()">Unbind</button>
        <button ng-click="binding()">Bind</button>
  </div>

JS

function test($scope) {
    $scope.content = 'Welcome';

     $scope.binding = function() {
       angular.element(document.getElementById('txtElem')).bind();
    };

    $scope.stopBinding = function() {
       angular.element(document.getElementById('txtElem')).unbind();
    };
};

Display

In my search for unbinding methods (http://jsfiddle.net/jexgF/), I couldn't figure out how to rebind when clicking the "Bind" button. Can anyone provide assistance?

Additionally, aside from binding and unbinding elements within <div> and <input>, does anyone know how to bind and unbind two <input> fields simultaneously?

Answer №1

In the example you provided, I am uncertain of where the test() function is located. However, it is considered an anti-pattern to manipulate the DOM in the controller.

A better approach would be to create a separate variable for the preview content that is independent from the input variable content.

If this logic truly belongs to the View layer, you can simply implement it within the View itself. The variable lastBound stores the last bound value of content:

<div ng-init="binding = true">
   <input ng-model="content">
   <button ng-click="binding = false">Unbind</button>
   <button ng-click="binding = true">Bind</button>

   <div ng-bind="lastBound = (binding && content) || lastBound"></div>
</div>

(Note: The use of ng-init here is purely for demonstration purposes - the actual setting of binding should be done in the controller).

EDIT:

If your goal is to bind to another ng-model, the solution may vary slightly but still involves using 2 variables:

<input ng-model="content" ng-change="preview = (binding && content) || preview">
<input ng-model="preview" ng-change="content = (binding && preview) || content">

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

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...

Error encountered when attempting to use the submit button in AngularJS

My goal is to create a simple Angular application that takes input of two numbers (n1 and n2) and then prints their sum. I have integrated Bootstrap for styling, but noticed that nothing was happening upon submission. To troubleshoot, I added an alert() fu ...

Leveraging AngularJS services within an Angular service

I am currently in the process of transitioning my AngularJS application to Angular. To facilitate this transition, I plan to create a hybrid application that combines both frameworks until the conversion is complete. However, I have encountered an issue wi ...

"Exploring ways to reattempt a route request upon encountering the $stateNotFound event within AngularUI Router

Managing a large AngularJS application can be quite challenging when it comes to splitting it into functional modules. Currently, all the modules are loaded on the initial page load as they are bundled into a single JavaScript file. However, I am looking t ...

Sending an Angular $http post request to a MVC action but the parameter is coming through as

After posting this content: $http.post(Common.blog.save, { blog: blog }) .then(saveBlogComplete) .catch(function(message) { }); The Fiddler output I receive is as follows: {"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\ ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Streamline repetitive scope attributes in AngularJS

After noticing that I was using a repetitive structure, I want to simplify it: <container> <clock property="data"></clock> <calendar property="data"></calendar> <alert property="data"></alert> </container ...

Angular Translate Directive Unleashes the Power of XSS Vulnerabilities

For my project, I have chosen to utilize the 'escape' method as the sanitization strategy for handling potentially harmful content. This includes implementing the translate directive in certain areas, as well as utilizing the translate filter in ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

Angular Jasmine Test produces incorrect ng-class result

During my experimentation with an Angular Directive, I encountered an issue where I utilized $compile to generate an instance of the directive in the Document Object Model (DOM). The element that the directive is linked to includes an ng-class attribute wi ...

Sending JSON data stored in $scope using AngularJS with AJAXPOST request

I am frustrated: I am currently working on an AngularJS project and struggling to correctly post data. I have filled out some HTML input fields, with values stored in a variable like $scope.product, and now I need to send this JSON structure of $scope.pro ...

Slicing an array in Javascript/Angular before it is officially initialized

Is it possible to specify the portion of an array to retrieve before making a $http GET request in Angular? I am aware of slicing arrays, but wondering if I can set this up in advance for better performance. In PHP, you can do something similar, but not ...

Retrieve the value of an unmatched ng-pattern field

<div> <input type="text" name="rate" ng-model="rate" ng-pattern="/^[0-9]+(\.[0-9]{0,2})?$/"/> </div> <span class="text-warning control-label"> {{rate}} ...

Uploading CSV file in Angular to populate the scope rather than sending it to the server

I need assistance with allowing users to upload a CSV file, which will then be displayed and validated. Rather than uploading the file directly to the server, I would prefer to keep it within scope until validation is complete. Unfortunately, Angular 1.5. ...

A guide to accessing an ngModel element within a reusable component

I have a specific ngModel component inside a reusable component that is not part of a form. I need to access it in order to make some changes, but when I try to do so using the code below, it returns undefined during OnInit. Can you advise me on how to pro ...

I am having trouble making an HTTP GET call to my API using AngularJS

I'm currently working on a Web Application and have encountered an issue with making HTTP GET calls from Angular to my API. The strange thing is that I've tested my API in both the browser and Postman (using Chrome) and it works perfectly fine. T ...

"AngularJS makes it easy for the logged-in user's information to be accessible and available across

I need to ensure that user information is accessible across all views after logging in. How can I adjust the code to be able to retrieve the pseudonym from another view? Could you provide an example as well? Below is my login controller: app.controller ...

Sharing data between pages in Ionic and Angular with POST requests

Currently, I am utilizing Ionic for developing a mobile application and have decided to incorporate very basic authentication (without any security measures) into the app. The process involves validating user credentials against a database through a POST r ...

Testing the performance of MEAN applications under heavy load

As I work on developing an application using the cutting-edge MEAN stack, I have successfully deployed the initial version to a server. This application comprises of a static HTML file (along with CSS and some images) as well as numerous JavaScript files. ...

Updating an object with AngularJS

Let's consider the code snippet below: var absenceType = {name: 'hello'}; this.newAbsenceType = angular.copy(absenceType); After making changes to this.newAbsenceType, you want to apply these changes to the original object. I have explore ...