Angular Data Binding With Passed Params
Solution 1:
You're running into a classic Javascript mistake, nothing to do with AngularJS. In Javascript, arrays and objects are always passed by reference. Assume the following:
this.productIds = [1,2,3]
$scope.productIds = this.productIds;
This will make an array, let's call it "A". It will then put a reference to that array in this.productIds and $scope.productIds.
If you now do this:
this.productIds = [4,5,6];
console.log(this.productIds);
console.log($scope.productIds);
then you will get:
[4,5,6]
[1,2,3]
Why? Because setting this.productIds
doesn't change the array. It changes which array this.productIds
POINTS TO.
There are a lot of options for fixing this. Here's a quick hack:
this.productIds.length = 0; // Truncate the existing array instead of making a new one
angular.forEach(productIds, function(entry) {
this.productIds.push(entry); // Copy the elements into our existing array
});
This isn't necessarily the most efficient, but it'll show you exactly what's going on.
Solution 2:
When you change the value outside of scope, you have to call $scope.$apply()
explicitly.
https://docs.angularjs.org/guide/scope
UPDATE
http://jsfiddle.net/qv31awmq/2/
puremvc.define({
name: "modules.search.view.components.Navigation",
constructor: function () {
varself = this;
var navigation = angular.module("navigation", []);
navigation.controller("ProductIDsController", function ($scope) {
self.$scope = $scope;
$scope.productIds = self.productIds;
});
angular.bootstrap(document.getElementById('navigation'), ['navigation']);
}
}, {
delegate: null,
$scope: null,
productIds: ["abc", "xyz", "test"],
init: function (productIds) {
varself = this;
// http://stackoverflow.com/questions/25941124/angular-data-binding-with-passed-params/25941351#25941351self.productIds.length = 0;
angular.forEach(productIds, function (entry) {
self.productIds.push(entry);
});
self.$scope.$apply();
}
}, {});
var nav = new modules.search.view.components.Navigation();
nav.init(['foo', 'bar']);
Solution 3:
I think the best way to do that would be to use a service to broadcast changes in productIds.
navigation.factory('ProductSvc',
['$rootScope', function($rootScope) {
return {
productIds : [],
changeProductIds: function(newIds){
this.productIds = newIds
$rootScope.$broadcast('changeIds');
}
}
}])
Controller linked to service :
navigation.controller("ProductIDsController", ['ProductSvc'],
function($scope, productSvc) {
...
$scope.$on('changeIds', function() {
$scope.productIds = ProductSvc.productIds;
})
}
Change your productId via the service (in a controller which handles user input for example)
ProductSvc.changeProductIds(newIds)
Post a Comment for "Angular Data Binding With Passed Params"