【问题标题】:Angular js unbind and bind dynamically not workingAngular js取消绑定和动态绑定不起作用
【发布时间】:2015-05-13 13:00:16
【问题描述】:

我有一个带有 ng-model 的 2 个输入和两个绑定这两个模型的元素,我希望当我单击一个按钮时它会切换绑定,即元素 1 绑定模型 2 和元素 2 绑定模型 1,它可以工作完美,但是当开始更改模型时,如果影响这两个元素!

为了说明这一点,我创建了一个plunker

如何解决这个问题?

app.js:

var app = angular.module('myApp', []);

app.controller('myController', function($scope,$compile) {
  $scope.model1="1";
  $scope.model2="2";

  $('#click').click(function () {

    $('#model1').attr('ng-bind','model2');
    $('#model2').attr('ng-bind','model1'); 
    angular.element($compile( $('#model1'))($scope));
    angular.element($compile( $('#model2'))($scope));
    $scope.$apply();

  });

});

【问题讨论】:

  • 您的 JSFiddle 中存在一些问题。你能更新一下吗?
  • 是的,我已经更新了,但我正在尝试向其中添加 Angular js 和 jquery 你可以尝试这样做吗?
  • @AmarAttilaZz 你想像这样交换变量吗jsfiddle.net/yBP5J/29
  • 不,我想保持模型的相同值,只切换我的 2 个元素的绑定,认为它可以通过切换它们的 ng-bind 属性来工作
  • 我创建了一个新的 plunker 而不是 jsFiddle 请参阅我原来帖子中的链接

标签: angularjs angular-ngmodel ng-bind


【解决方案1】:

这是一个有效的plunker 示例;

永远不要直接在控制器中操作 DOM。通常你不会自己操纵 dom。你使用 angular 指令来做你想做的事。请记住,如果您想使用 jQuery,您可能会以错误的方式使用它,并且有一种方法可以从 Angular 实现,而无需调用 jQuery。

Javascript

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,$compile) {


  $scope.name = 'World';

  //input1 and input2 will contain the key of the variable bind to the input.
  $scope.input1 = "value1";
  $scope.input2 = "value2";
  $scope.model = {
     value1 : 1,
     value2 : 2
  }

  // Here is my switch function. I just switch the keys and angular will do the rest.
  $scope.switch = function(){
    var tmp = $scope.input1;
    $scope.input1 = $scope.input2;
    $scope.input2 = tmp;
  }
});

HTML

  <body ng-controller="MainCtrl">
    <!-- Angular provide a directive called ng-click to bind function on clic for the html element -->
    <button ng-click="switch()">switch</button>
    <!-- Here i bind the property of an object. I'll just update the key in input1 to change which property is bind-->
    <input type="text" ng-model="model[input1]" />
    <input type="text" ng-model="model[input2]" />
    <h5 id="model1" ng-bind="model[input1]"></h5>
    <h5 id="model2" ng-bind="model[input2]"></h5>
  </body>

希望对您有所帮助,如果您想进一步解释,请继续。

【讨论】:

  • @AmarAttilaZz 记住 jQuery = 几乎从不在角度范围内。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
  • 2019-09-17
  • 2017-06-16
  • 2017-02-22
  • 1970-01-01
相关资源
最近更新 更多