【发布时间】:2014-06-07 14:05:39
【问题描述】:
在建立控制器并将 $scope 设置为使用工厂方法(用于 GET 和 POST)时,在页面加载过程中,我的 POST 被触发。下面是代码示例。为了解决这个问题,我将“POST”包装在一个 jQuery click 事件函数中,一切正常。下面是代码。
在控制器(app.js)中:
demoApp.controller('SimpleController', function ($scope, simpleFactory) {
$scope.customers = [];
init();
function init() {
$scope.departments = simpleFactory.getDepartments();
}
// Works fine
$('#myButton').click(function () {
simpleFactory.postDepartments();
});
// When setting the "scope" of a controller, during page load the scope factory method is fired off!
// seems like a defect.
//$scope.addDepartment = simpleFactory.postDepartments();
});
所以,这里发生的事情是,如果我在页面加载时取消注释 $scope.addDepartment = ...,则会调用 postDepartments() 工厂方法。这不是期望的行为。这是我连接 Html Dom 元素的方式:
<button id="myButton" data-ng-click="addDepartment()">Add Department</button>
所以,如果我取消注释,就像我上面所说的,它会在用户点击按钮之前添加部门。但是,使用 jQuery 方式处理它,没有问题。
这是一个已知的错误吗?这是预期的功能吗?另外,看看下面的工厂,可能问题出在哪里?
demoApp.factory('simpleFactory', function ($http) {
var departments = [];
var factory = {};
factory.getDepartments = function () {
$http.get('/Home/GetDepartments').success(function (data) {
for (var i = 0; i < data.length; i++) {
departments.push({ desc: data[i].desc, id: data[i].id });
}
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
return departments;
};
factory.postDepartments = function () {
$http.post('/Home/PostDepartment', {
cName: 'TST',
cDescription: 'Test Department'
}).success(function (data) {
departments.push({ desc: 'Test Department', id: departments.length + 1 });
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
return departments;
};
return factory;
});
【问题讨论】:
-
如果您在初始化时不需要它,为什么要使用初始化函数?
标签: javascript jquery angularjs scope