我试图在一个带有getTemplates函数的服务中将一个对象添加到我的数组savedTemplates中。 我已经为此使用了一项服务,以便在多个视图中访问模板。 不幸的是,如果我尝试调用我的函数,则没有任何反应。
services.js:
<script>
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("user_login");
// Retrieve
document.getElementById("user_pass").innerHTML = localStorage.getItem("user_pass");
} else {
document.getElementById("user_pass").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
template-save.html:
.factory('templateData', function(){
var savedTemplates = [
{"name":"Adam Müller", "iban":"AT29100020003000","image":"adam.jpg"},
{"name":"Ben Streicher","iban":"AT34900080007000","image":"ben.png"},
{"name":"Max Krossmann","iban":"AT23400050006000","image":"max.png"}
];
var getTemplates = function(){
return savedTemplates;
};
var addTemplates = function(insertName,insertIban){
savedTemplates.push=({"name": insertName, "iban": insertIban, "image": 'mike.png'});
alert("This is savedTemplates:" + savedTemplates);
};
return {
getTemplates:getTemplates,
addTemplates:addTemplates
};
})
我会非常感激任何帮助,因为我已经非常绝望了。
答案 0 :(得分:0)
这是一个示例代码段。
您的工厂addTemplates
代码中也存在问题,您应该使用savedTemplates.push ({ ... }]
,而不是savedTemplates.push = ({ ... }]
<强>段强>
angular.module('app', []);
angular.
module('app')
.controller('ExampleController', ['$scope', 'templateData', function($scope, templateData) {
$scope.addTemplates = templateData.addTemplates;
}])
.factory('templateData', function() {
var savedTemplates = [{
"name": "Adam Müller",
"iban": "AT29100020003000",
"image": "adam.jpg"
},
{
"name": "Ben Streicher",
"iban": "AT34900080007000",
"image": "ben.png"
},
{
"name": "Max Krossmann",
"iban": "AT23400050006000",
"image": "max.png"
}
];
var getTemplates = function() {
return savedTemplates;
};
var addTemplates = function(insertName, insertIban) {
savedTemplates.push ({
"name": insertName,
"iban": insertIban,
"image": 'mike.png'
});
console.log("This is savedTemplates:" + JSON.stringify(savedTemplates, null, 2));
};
return {
getTemplates: getTemplates,
addTemplates: addTemplates
};
});
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="addTemplates('Marty McFly', 'BTTF900080007000')">
Speichern
</button>
</body>
</html>