Angular允许您使用指令的作用域设置双向数据绑定。有谁知道使用指令的控制器设置双向数据绑定的简单方法。使用指令的角度控制器进行双向数据绑定
例如:http://plnkr.co/edit/TIxXrvYpP0na4xEeYLgS?p=preview
HTML
<body ng-app="myApp" ng-controller="MyCtrl as ctrl">
Controller Test: {{ctrl.test}}
<div dir test="ctrl.test"></div>
</body>
JS
var MyCtrl = function($timeout) {
this.test = {msg: 'hello'};
var _this = this;
$timeout(function() {
_this.test = {msg: 'good bye'};
}, 1000);
}
angular.module('myApp', []).directive('dir', function() {
return {
scope: {
test: '='
},
template: '\
<div>Directive Scope Test: {{test}}</div>\
<div>Directive Controller Test: {{dCtrl.test}}</div>',
controller: function($scope) {
this.test = $scope.test;
},
controllerAs: 'dCtrl'
}
});
在上述MyCtrl
的test
变量的示例绑定到dir
指令的范围。但是,当变量分配给指令的控制器(this.test = $scope.test;
)时,双向绑定被破坏。
我将范围变量分配给控制器仅仅是因为在使用“控制器为”语法时,在使用范围变量和控制器变量之间来回转换有点尴尬。然而,我能想到的最佳解决方案是直接访问$scope
之外的变量。有没有人有与“控制器为”风格控制器更好的解决方案。
正是我一直在寻找。谢谢!这可能会导致缩放并使我切换到1.3。 – rob 2014-09-23 23:54:34
@rob不客气..还有很多很棒的功能让我在新项目中升级.. :) – PSL 2014-09-24 00:05:06