私は AngularJS の controllerAs 構文に慣れてきましたが、サービス変数への単純なバインディングを行う必要があるときに問題が発生しました。通常、$scope.$watch
or$scope.$on
はそうしますが、それには を注入する必要があり$scope
、controllerAs の目的を無効にしているようです。
現在私が持っているのは、ボタンの1つをクリックして を呼び出したconfig.setAttribute(attr)
後、コントローラーはサービスのsetAttribute
関数を呼び出しますが、 は呼び出さないgetAttribute
ため、config.attribute
変更されません。
私がこれにどのように取り組んでいるのか、私が見落としているものはありますか? 代わり$scope
に使用するコントローラー構文を挿入または変更する必要がありますか?$scope
意見:
<div data-ng-controller="ConfigCtrl as config">
<h3>Customize</h3>
<pre>Current attribute: {{config.attribute}}</pre>
<label>Attributes</label>
<div data-ng-repeat="attr in config.attributes">
<button ng-click="config.setAttribute(attr)">{{attr.name}}</button>
</div>
</div>
サービス:
(function() {
'use strict';
angular.module('app')
.factory('Customization', Customization);
function Customization() {
var service = {
attribute: null,
getAttributes: getAttributes,
setAttribute: setAttribute,
getAttribute: getAttribute
}
return service;
/////
function getAttributes() {
return [
{name: 'Attr1', value: '1'},
{name: 'Attr2', value: '2'} // etc.
];
}
function setAttribute(attr) {
service.attribute = attr;
}
function getAttribute() {
return service.attribute;
}
}})();
コントローラ:
(function(){
'use strict';
angular.module('app')
.controller('ConfigCtrl', ConfigCtrl);
function ConfigCtrl(Customization){
var vm = this;
vm.attribute = Customization.getAttribute(); // bind
vm.attributes = [];
// Functions
vm.setAttribute = Customization.setAttribute;
init();
/////
function init(){
// Get attributes array
vm.attributes = Customization.getAttributes();
}
}})();