How can I add custom fields to angular scope along with passed fields as attributes, as the following:
angular.module('app')
.directive("myDirective", function(){
function NewObj()
{
this.id = 0;
this.name = "";
}
return{
restrict: "E",
templateUrl:"partials/directives/temp.html",
scope:{
viewId:"=",
dataObj: new NewObj() //This is the custom obj
}
}
}
When I do so, I get invalid isolated scope definition. How can this be accomplised ?
Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.
The best way to pass an object to an angular directive is by using the &. When you use &, angular compiles the string as an expression and sets the scope variable in your directive to a function that, when called, will evaluate the expression in the context of the directive's parent's scope.
Scope in a Directive Well, all of the directives have a scope associated with them. This scope object is used for accessing the variables and functions defined in the AngularJS controllers, and the controller and link functions of the directive.
What is Custom Directive? A Custom Directive in AngularJS is a user-defined directive that provides users to use desired functions to extend HTML functionality. It can be defined by using the “directive” function, and it replaces the element for which it is used.
The scope in a directive can only be one of '=', '&', '@'. To do what you want, you can try something like:
angular.module('app')
.directive("myDirective", function() {
function NewObj() {
id = 0;
this.name = "";
}
return {
restrict: "E",
templateUrl:"partials/directives/temp.html",
scope: {
viewId:"=",
},
controller: ['$scope', function($scope) {
$scope.dataObj = new NewObj();
}]
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With