这是一个有效的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>
希望对您有所帮助,如果您想进一步解释,请继续。