0
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
firstname:<input type="text" ng-model="data.firstName">
lastname:<input type="text" ng-model="data.lastName">
<br>name is : <strong>{{data.firstName}} {{data.lastName}}</strong>
</div>
<div ng-controller="SecondCtrl">
name in 2nd controller: {{data.firstName}} {{data.lastName}}
<button ng-click="updateData('kv','a')">click</button>
</div>
<button onclick = "ChangeEvn()"/>
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.factory('MyService', function(){
return {
data: {
firstName: '',
lastName: ''
},
update: function(first, last) {
this.data.firstName = first;
this.data.lastName = last;
}
};
});
myApp.controller('FirstCtrl', function($scope, MyService){
$scope.data = MyService.data;
});
myApp.controller('SecondCtrl', function($scope, MyService){
$scope.data = MyService.data;
$scope.updateData = function(first, last) {
MyService.update(first, last);
}
});
function ChangeEvn()
{
alert("Ok");
myApp.factory.update("Hello", ".....");//doesn't work
}
</script>
</body>
</html>
在上面的代碼中,使用工廠在兩個控制器之間傳遞值。現在我想使用按鈕單擊來更新名和姓。按鈕點擊功能在控制器之外(我要求)。現在如何訪問控制器外的更新myApp.factory.update(「Hello」,「.....」);這種說法不工作如何訪問控制器外部工廠的功能