假設我們想與大家分享控制器之間的產品對象。在這裏,我已經創建了一個名爲SharedDataService的AngularJS服務爲顯示在下面的代碼片段:
myApp.service('SharedDataService', function() {
var Product = {
name: '',
price: ''
};
return Product;
});
接下來讓我們繼續前進,並使用SharedDataService兩個不同的控制器。在控制器中,我們使用上一步中創建的服務。可以創建控制器,如下圖所示:
var myApp = angular.module("myApp", ['CalService']);
myApp.controller("DataController1", ['$scope', 'SharedDataService',
function ($scope, SharedDataService) {
$scope.Product = SharedDataService;
}]);
myApp.controller("DataController2", ['$scope', 'SharedDataService',
function ($scope, SharedDataService) {
$scope.Product = SharedDataService;
}]);
在視圖,我們可以簡單地使用控制器,如下圖所示列表:
<h2>In Controller 1h2>
<input type="text" ng-model="Product.name" /> <br/>
<input type="text" ng-model="Product.price" />
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
<hr/>
<div ng-controller="DataController2">
<h2>In Controller 2h2>
<h3>Product {{Product.name}} costs {{Product.price}} h3>
div>
出色答卷水平。我會用jsbin來測試。謝謝。 –
我這樣做,但沒有工作: – Alfredo
這是控制器中的方法,從視圖獲取數據 - > $ scope.indexData = function(){var 0; 0; newString = $ scope.searchBox; dataService.setVal(newString); $ window.location.href =「#/ search」; - >這是主要部分,但不會重定向到searh路由... – Alfredo