Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs custom directive isolated scope custom fields

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 ?

like image 349
Sameh K. Mohamed Avatar asked Apr 26 '14 11:04

Sameh K. Mohamed


People also ask

What is isolate scope in AngularJS?

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.

How do I pass data from one directive to another directive in AngularJS?

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.

What is scope in AngularJS directive?

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 in AngularJS?

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.


1 Answers

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();
        }]
    };
});
like image 122
Andrea Bergia Avatar answered Oct 26 '22 03:10

Andrea Bergia