I can't clarify for myself how to deal with $scope in Angularjs. Although I've resolved my current issue other way, still I need help to get comprehension of $scope usage.
I have the following form (simplified for this example). Index.html:
<form class="form-horizontal" ng-controller="AddItemController as addItemCtrl">
<fieldset>
<legend>New item</legend>
<div class="form-group">
<label for="submittedBy" class="col-lg-2 control-label">Submitted by</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="submittedBy" ng-model="addItemCtrl.item.submitted_by" placeholder="Your name here">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<!--button class="btn btn-default">Cancel</button-->
<button type="submit" class="btn btn-primary" ng-click="addItemCtrl.addItem()">Submit</button>
</div>
</div>
</fieldset>
</form>
app.js:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
var table = angular.element($("#body")).scope();
table.items = data;
});
**this.item={};**
}
}]);
All I want is to get data from the form, send it to the server, get response, update table and then clear the form. The last part is my issue. I am currenly using this.item={} to handle it. But I do want to call it using $scope, so it should be $scope.item={} and then I want to move it inside addItem function. Unfortunately it's not working for either case.
I have this code and it is working as intended, but it seems I just got lucky/unlucky to make it without understanding mechanism.
app.controller('ItemController', ['$scope','$http', function ($scope, $http) {
function getItems(){
$http({
url: "get_items",
method: "GET"
}).
success(function(data, status, headers, config) {
$scope.items = data;
});
}
getItems();
}]);`
UPDATE. This is how my AddItemController looks like at the moment:
app.controller("AddItemController", ['$scope','$http', function ($scope, $http) {
$scope.item = {};
this.addItem = function() {
$http({
url: "add_item",
method: "GET",
params: this.item
}).
success(function(data, status, headers, config) {
$scope.$$prevSibling.items = data;
$scope.addItemCtrl.item={};
});
}
}]);
It works like I wanted it to. But I don't like $scope.$$prevSibling.items = data; statement, I use it to refresh table which is handled by ItemController, is there a more elegant way to do that?
var scope= angular.element($("#body")).scope();scope.items = data;If so, I have renamed it in the example, so it doesn't mess with my main issueItemControlleris responsible for the table and using its$scopeworks fine.AddItemControllerwas implemented for the form handling, so yes, it should have it's own$scope$scope.item={}inside the success callback should work. Are you sure that the problem is on that call? Is there any error in the console?$scope.item={}