如果你是在1.3 RC版,您可以使用bindToController
選項,有2路的約束範圍變量可以在控制器上的約束。否則,你將不得不手動將屬性映射到控制器實例(這是一個痛苦),或者只是使用常規語法(沒有控制器)來進行2種綁定屬性。所以你可以在指令配置中使用和bindToController:true
。
bindToController
- 當分離物範圍被用於組分(見上文),並且
controllerAs
被使用,bindToController
將
- 允許組件有其屬性綁定到控制器,而不是範圍。當實例化控制器
- 時,隔離範圍綁定的初始值已經可用。
(function(){
var myApp = angular.module('plunker', []);
var helloEC5 = function(){
this.pants = "jeans";
};
helloEC5.prototype = {
firstName: 'Seeya',
lastName: 'Latir',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName (name) {
var words = name.toString().split(' ');
this.firstName = words[0] || '';
this.lastName = words[1] || '';
}
};
myApp.controller('HelloEC5', helloEC5);
myApp.directive('myDirective', function() {
return {
scope: { pants: '='},
controllerAs: 'my',
controller: function(){},
bindToController:true,
template: '<h1>{{my.pants}} - myDirective.pants = {{ my.pants }}</h1><input ng-model="my.pants">'
}
});
})();
<script data-require="[email protected]" data-semver="1.3.0-rc.1" src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script>
<div ng-app="plunker">
<div ng-controller="HelloEC5 as EC5">
<p>HelloEC5 says my name is: {{EC5.fullName}} wearing {{EC5.pants}}!</p>
<label>Pants:</label>
<input ng-model="EC5.pants" type="text" />
<label>FirstName:</label>
<input ng-model="EC5.firstName" type="text" />
<div my-directive="" pants="EC5.pants"></div>
<hr />
<label>Setting HelloEC5.fullName:</label>
<input ng-model="EC5.fullName" />
</div>
</div>
來源
2014-09-21 18:24:07
PSL
我不完全掌握你想達到什麼目的,但如何對這種筆嗎? http://codepen.io/anon/pen/xzmiC – 2014-09-21 18:14:00
@Bonatoc OP想要將屬性附加到指令的控制器實例,而不是直接指向作用域。 BUt最終都是n範圍。控制器別名成爲範圍上的一個屬性。 – PSL 2014-09-21 18:32:43
@Botanoc,你的例子直接綁定到EC5控制器,我不想那樣。指令只應該意識到它所綁定的屬性。我試圖將幾個想法混合在一起,EC5 getter和setter(如果你看起來很接近真的很棒),控制器作爲一個對象(oo controller),然後雙重綁定到一個指令的本地範圍。 – httpete 2014-09-21 21:16:05