简体   繁体   中英

Angularjs: In a custom directive I need to read argument passed with ngClick method

In my custom directive, in order to set the right template, I need to be able to use an argument that has been passed like so:

ng-click="loadTabContent('socialnetwork')"

In my controller I have something like this:

$scope.loadTabContent = function(passedArgument){
    $scope.content = PostsResource.query();
    // below I'd like to attach the above argument onto $scope object like so
    $scope.networkCalled = passedArgument;
}

Then in my directive I'd do this:

// linker function
var linker = function(scope, element, attrs){
    // does NOT work
    element.html( getTemplate(scope.networkCalled) );

    // does work, provided I have type="somename" on my directive element in HTML
    element.html( getTemplate(attrs.somename) );

    $compile( element.contents() )(scope);
}

I suspect that the value of the argument is not attached to the $scope object in time, so it's not available when I need it. Is $apply or any other built-in function supposed to solve this problem?

EDIT:

I left out an importan piece of my directive I believe:

        return {
            restrict: "A",
            replace: true,
            link: linker,
            scope: {
                content: '='
        }

If I understand correctly, you're binding your directive scope.networkCalled with a controller's scope property. Unfortunately, at that time angular does not update its bindings yet.

When you use isolate scope, remember to declare your networkCalled property:

scope: {
      content: '=',
      networkCalled:'='
}

And bind the property in your html:

<div your-directive network-called="networkCalled"></div>

Try $watch to get notified when the binding is updated:

var linker = function(scope, element, attrs){

    scope.$watch("networkCalled",function (value){
       if (value){
          element.html( getTemplate(value) );

          $compile( element.contents() )(scope);
       }
    });
  }

For more information: AngularJS : Directive not able to access isolate scope objects

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