Reputation: 851
I am new to AngularJS and was wondering how I would go about copying the values in my parent scope to my directive scope with no bindings (2 separate instances). Currently my implementation goes as is, with my newHostTemplate calling {{newHost.ipAddress}}
however I want newHost to be from the directives scope and not the parent.
host.directive('newHost', function(){
return {
restrict: 'E',
template: '<div ng-include="getTemplateUrl()"></div>',
scope: true,
link: function(scope, element, attr) {
scope.newBox = function() {
scope.getTemplateUrl = function() {
return 'hosts/newHostTemplate.html';
}
}
}
}
});
host.controller('hostsController', function($scope, $http, $window, $rootScope){
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
console.log("failed to change routes");
});
$scope.newHost = {};
$scope.addNewHost = function() {
$http({
method : 'POST',
url : 'http://192.168.0.99:5000/newHost',
data : JSON.stringify($scope.newHost), // pass in data as strings
})
.success(function(data) {
console.log(data);
$scope.newBox()
$scope.newHost = {}
//on success we want to close the modal and reset the data
$scope.dismiss()
});
};
});
Currently when I run this I get an error saying newBox is not a function.
Upvotes: 0
Views: 87
Reputation: 804
You want to isolate the scope. Instead of scope: true, do scope: {}.
Any explicit input from the parent to the directive would be through defined scope variables:
scope: {
twoWayBoundInputOne: '=',
staticStringInputTwo: '@',
functionThree: '&'
}
Also, recommended architecture is to put reusable code, such as AJAX requests into a service. https://docs.angularjs.org/guide/services
Inject the service into the directive and controller the same way you inject $scope or $http.
Your service may look like:
/* global bz_app */
host.factory('hostsService', ['$http',
function ($http) {
return function () {
this.add = function () {
return $http({
method : 'POST',
url : 'http://192.168.0.99:5000/newHost',
data : JSON.stringify($scope.newHost), // pass in data as strings
});
};
this.templateUrl = function() {
return 'hosts/newHostTemplate.html';
};
};
}]);
// then in your controller or directive you can do this, to get an instance that doesn't get impacted by other instances.
scope.host = new HostsService();
Upvotes: 2