Angular js解绑并动态绑定不起作用

时间:2015-05-13 13:00:16

标签: angularjs angular-ngmodel ng-bind

我有一个带有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();

  });

});

1 个答案:

答案 0 :(得分:1)

这是一个有效的plunker示例;

永远不要直接在控制器中操作DOM。通常你不会操纵自己。您可以使用angular指令来执行您想要的操作。请记住,如果你想使用jQuery,你可能会以错误的方式做到这一点,并且有一种方法可以从角度进行操作而不需要调用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>

希望它能帮到你,如果你想进一步解释的话。