我想要角度控制器传递参数($scope
)
但$scope.setName = function()
不起作用,
我该怎么办...请〜
脚本
var myApp = angular.module("myApp", []);
myApp.factory('Data', function() {
return {
name: "Ting"
}
});
myApp.controller('FirstCtrl', function($scope, Data) {
$scope.data = Data;
$scope.setName = function() {
Data.name = "Jack";
}
});
myApp.controller('SecondCtrl', function($scope, Data) {
$scope.data = Data;
$scope.setName = function() {
Data.name = "Moby";
}
});
HTML
<body ng-app='myApp'>
<input type="text" ng-model="person.name"/>
<div ng-controller="FirstCtrl">
{{person.name}}
<button ng-click="setName()">set name to jack</button>
</div>
<div ng-controller="SecondCtrl">
{{person.name}}
<button ng-click="setName()">set name to jack</button>
</div>
</div>
</body>
答案 0 :(得分:0)
它工作正常。
您正在打印模型而非服务。
由于服务是控制器上的单例更改,它将为每个活着的控制器进行更改
var myApp = angular.module("myApp", []);
myApp.factory('Data', function() {
return {
name: "Ting"
}
});
myApp.controller('FirstCtrl', function($scope, Data) {
$scope.data = Data;
$scope.setName = function() {
Data.name = "Jack";
}
});
myApp.controller('SecondCtrl', function($scope, Data) {
$scope.data = Data;
$scope.setName = function() {
Data.name = "Moby";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app='myApp'>
<input type="text" ng-model="person.name"/>
<div ng-controller="FirstCtrl">
{{data.name}}
<button ng-click="setName()">set name to jack</button>
</div>
<div ng-controller="SecondCtrl">
{{data.name}}
<button ng-click="setName()">set name to jack</button>
</div>
</div>
</body>