【发布时间】:2014-09-23 23:40:37
【问题描述】:
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 访问变量。有没有人有更适合“控制器作为”样式控制器的解决方案。
【问题讨论】:
标签: javascript angularjs data-binding angularjs-directive