Angular Js $范围

时间:2014-04-23 00:02:53

标签: javascript jquery angularjs scope

在建立控制器并将$ scope设置为使用工厂方法(对于GET和POST)时,在页面加载过程中,我的POST被触发。下面是代码示例。为了解决这个问题,我把#34; POST"在jQuery点击事件功能,一切顺利。以下是代码。

在控制器(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;
});

1 个答案:

答案 0 :(得分:2)

试试这个:

$scope.addDepartment = function() {
    return simpleFactory.postDepartments();
}

如果您决定,这也将允许您将来传递参数。你最初拥有它的方式,你既要分配功能又同时调用它。

然后,您可以在ngClick中使用它:

<button ng-click="addDepartment()">Add Department</button>

不要在你的控制器中使用jQuery click方法,它会将关注点分成模型,视图,控制器等等。这就是指令的用途。