似乎当我为服务/工厂中的变量分配一个新值时,它会破坏绑定,控制器会停止更新值,除非我调用控制器中的$scope.verify
函数,它只打印服务对象到控制台,然后绑定更新一次。我在skypeClient
工厂分配了错误的值吗?
property.changed(function (_status) {
state = _status;
console.log("New State" + state);
});
实施例。我执行$scope.signIn()
并且绑定更新到signingIn
但是当值更改为SignedIn
时(通过控制台验证),除非我执行{{1},否则控制器不会更新为SignedIn
对于$scope.verify()
之后的每一次更改都来自之后。
见下面的代码:
控制器
skypeClient.state
服务
controller('loginCntrl', function ($scope,skypeClient) {
$scope.skypeClient = skypeClient;
$scope.signIn = function () {$scope.skypeClient.signIn($scope.user, $scope.password)}
$scope.signOut = function(){$scope.skypeClient.signOut()}
$scope.verify = function () {
console.log(skypeClient);
console.log($scope.skypeClient);
}
});
HTML
.factory('skypeClient', function () {
//Service Properties
var client = new Skype.Web.Model.Application;
var state = 'SignedOut';
var property = property = client.signInManager.state;
//Initialize Listeners
var init = function () {
client.signInManager.state.when('SignedIn', function () {
console.log('Signin:' + state); // This outputs the correct value
});
property.changed(function (_status) {
state = _status; //<--WHERE VALUE IS UPDATED
console.log("New State" + state);
});
}
//Signin Function
var signIn = function (username, password) {
client.signInManager.signIn({
username: username,
password: password
}).then(function () {console.log('LoggedIn');});
}
var signOut = function () {
client.signInManager.signOut()
.then(function () {
this.isSignedIn = false;
}, function (error) {
this.erros.push(error);
this.errorCount++;
});
}
init();
return {
signIn: signIn,
signOut, signOut,
state: function(){return state}
}
});
答案 0 :(得分:0)
让我试一试。
如果可以,请尝试使状态成为需要在绑定中显示的范围的变量。
<强>控制器强>
controller('loginCntrl', function ($scope,skypeClient) {
...
$scope.state = skypeClient.state();
...
});
<强> HTML 强>
(Current Signin State: {{ state }} )
现在,在您的控制器中,您可以从skypeClient向状态变量添加$ watch。如果我是正确的,事情应该更新,并取得更大的成功。
控制器(再次)
controller('loginCntrl', function ($scope,skypeClient) {
...
$scope.state = skypeClient.state();
...
// Add this $watch
$scope.$watch(skypeClient.state, function (newValue, oldValue) {
if (newValue !== oldValue) {
$scope.state = newValue;
}
});
});