2015-05-13 15 views
0

我有NG-模型的2個輸入和兩個元件結合兩個模型,我想,當我點擊一個按鈕,它切換綁定IA方式元件1結合模型2和元素2綁定模型1,它完美地工作,但是如果影響兩個元素,開始更改模型!角JS拆散並綁定動態不工作

來說明它,我已經創建了一個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(); 

    }); 

}); 
+0

JSFiddle中存在一些問題。你能否更新它? – Vasanthan

+0

是的,我已經更新,但我想添加角js和jQuery它可以嘗試這樣做嗎? –

+0

@AmarAttilaZz你要像變量的交換這個https://jsfiddle.net/yBP5J/29/ –

回答

1

這裏是一個工作plunker示例;

切勿直接在控制器中操作DOM。通常你不會自己操縱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> 

希望它可以幫助你,如果你想進一步解釋下去。

+0

它完美的作品謝謝 –

+0

@AmarAttilaZz記住jQuery =幾乎從不在角度內。 – Okazari