简体   繁体   中英

how to pass multiple scope variables into custom directive in angularjs

I am trying to pass 2 scope variables from controller into a custom directive and having problem in accessing both of them.Model is same for the directive and controller. Here is the code:

Html:

<myDirective data="var1" item="var2"></myDirective>

Controller:

$scope.var1="abc";
$scope.var2="xyz";

Directive:

  app.directive('myDirective', function () {

        return {
            restrict: 'E', //E = element, A = attribute, C = class, M = comment         
            scope: {
                    var1: '='
                     var2:'='

                     },

            templateUrl: 'myTemplate.html',

            link: function ($scope, element, attrs) {


                    } 
        }
    });

TemplateUrl: myTemplate.html

 <div>{{var1}}</div>  // This works
 <div>{{var2}}</div>  // This doesn't works

Any idea how can I use both?

Make these changes in your code

<popover data="var1" item="var2"></popover>

JS

app.directive('popover', function () {
    return {
        restrict: 'E', //E = element, A = attribute, C = class, M = comment
        scope: {
            data: '=',
            item: '='
        },
        templateUrl: 'myTemplate.html',
        link: function (scope, element, attrs) {
           console.log(scope.data, scope.item);
        } 
     }
});

Change your template to match the names declared in the DDO.

<myDirective var1="var1" var2="var2"></myDirective>

Avoid using data as an attribute name. That is a reserved prefix that is stripped during normalization. For more information on attribute normilization, see AngularJS Developer Guide - Directive Normilization .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM