【发布时间】:2015-11-01 03:51:04
【问题描述】:
我熟悉 AngularJS 中的 controllerAs 语法,当我需要对服务变量进行简单绑定时遇到了问题。通常$scope.$watch 或$scope.$on 可以,但这会涉及注入$scope,这似乎违背了controllerAs 的目的。
目前我所拥有的是,在单击其中一个按钮并调用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();
}
}})();
【问题讨论】:
-
注入
$scope不会破坏controllerAs 的目的。这就是重点——当需要$watch和$on之类的服务时注入$scope,而不是默认情况下发布 ViewModel 属性。 -
感谢 cmets,他们绝对解决了我的困惑。
标签: javascript angularjs angularjs-scope watch angularjs-controlleras