我已經編寫了下面的代碼來從輸入字段獲取值並保存它。 我定義了一個全局變量,並將其中的輸出放在app.factory中使用。問題是「x」只能在「更新函數」內部讀取,並且在其外部的任何位置未定義。 我該如何解決這個問題?
var app = angular.module('bomApp', ['bomGraph']);
app.controller('bomController', ['$scope', 'appService', '$rootScope', function ($scope, appService, $rootScope) {
var get = function() {
appService.get().then(function (promise) {
$scope.graph = {
options: {
"hierarchicalLayout": {
"direction": "UD"
},
"edges": {
"style":"arrow-center",
"color":"#c1c1c1"
},
"nodes": {
"shape":"oval",
"color":"#ccc"
}
},
data: {
nodes: promise.nodes,
edges: promise.edges
}
};
});
};
$scope.newNode = {
id: undefined,
label: undefined,
level: undefined,
parent: undefined,
};
$scope.arrNode = {};
$scope.update = function (nodes) {
$scope.arrNode = angular.copy(nodes);
$rootScope.x = angular.copy(nodes);
};
$scope.newEdge = {
id: undefined,
from: undefined,
to: undefined
};
$scope.arrEdge = {};
$scope.updateE = function (edges) {
$scope.arrEdge = angular.copy(edges);
};
get();
}]);
app.factory('appService', ['$q', '$http', '$rootScope', function ($q, $http, $rootScope) {
console.log($rootScope.x);
return {
get: function (method, url) {
var deferred = $q.defer();
$http.get('data.json')
.success(function (response) {
deferred.resolve(response);
})
return deferred.promise;
},
};
}]);
謝謝你..我對Angular完全陌生,你可以讓它更清楚一點,以及如何編寫它? – 2015-03-03 10:22:29
更新了我的答案。請檢查 – mohamedrias 2015-03-03 10:32:29
謝謝您的時間,它是可訪問的,但是正在運行console.log()返回以下錯誤:TypeError:無法讀取屬性'x'的未定義 在Object。 (在angular.min.js:27) at c。(angular.min.js:26) at d (angular.min.js:26) at Object.instantiate(angular.min.js:27) at $ get(angular.min.js:50) at angular.min.js:42 at m(angular .min.js:6) at k(angular.min.js:42) – 2015-03-03 10:49:49