我试图解决这个代码示例中指令内的一次性绑定值(obj.value)正在更新的原因吗?
更新第一个字段只会按预期更新指令内的绑定值一次。然后,在指令内部,当单击"编辑"时,它还将更新一次性绑定值并更新父范围。再次更新第一个字段不会更改指令内的值。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl" ng-model-options="{updateOn: 'blur'}">
Enter value here first, then press edit:<br>
<input type="text" ng-model="t.value"><br>
<br>
Press edit, change the value and press copy:
<my-directive obj="t"></my-directive><br><br>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function() {
var directive = {};
directive.restrict = 'E';
directive.template = '<div ng-switch="edit">\
<div ng-switch-default>[{{ ::obj.value }}]<button ng-click="toggle()">edit</button></div>\
<div ng-switch-when="true">\
<input type="text" ng-model="clone.value">\
<button ng-click="copy()">copy</button>\
</div>\
</div>';
directive.scope = {
obj: '='
};
directive.controller = function($scope) {
$scope.edit = false;
$scope.toggle = function() {
$scope.edit = true;
$scope.clone = angular.copy($scope.obj);
}
$scope.copy = function() {
$scope.obj = angular.copy($scope.clone);
$scope.edit = false;
}
}
return directive;
});
myApp.controller('myCtrl', function(){
});
</script>
</body>
答案 0 :(得分:1)
In 1.3 they added a new syntax for helping with one-way binding, "::". So you just need to change your directive implementation to obj="::t"
.
Here's an update to your plnkr: http://plnkr.co/edit/7lsiX1ItPiQoVpJcQ6iW?p=preview
Here's a nice article that explains a bit more
答案 1 :(得分:0)
这是因为ng-switch。每次重新计算表达式时,指令都会被“重绘”。每次都是这样,一次表达也会被重新计算。
如果您将模板更改为:
directive.template = '{{::obj | json}}<div ng-switch="edit">
etc...
你会看到它不会改变,因为它在ng-switch之外。