0

I'm fairly new to AngularJS Directives and was wondering how I could implement passing a custom string, which is a url that contains a controller variable, to be used later on by that controller?

Calling Directive

<div ng-controller="MyController">
    <my-custom-form after-submit="group/{{insertedId}}" />
</div>

Directive

app.directive('myCustomForm', function() {
    return {
        templateUrl: 'myCustomForm.html',
        link: function(scope, element, attr) {
            scope.loadUrl = attr.afterSubmit;
        }
    }
});

Controller

app.controller('MyController', function($scope, $location, $http) {
    $scope.loadUrl = '';
    $scope.insertedId = NULL;
    $http({
        method:'POST',
        url:'edit.php',   
        data:formData
    }).success(function(response) {
        $scope.insertedId = response.dbInsertedPrimaryId; // used in "after-submit"
        $location.path($scope.loadUrl); 
    });
});

So when $location.path() called it sends me to a url for example:

http://example.com/group/22

The reason for this is so that I can pass a specific/different url each time the directive is used, like so

<div ng-controller="MyController">
    <my-custom-form after-submit="user/{{insertedId}}" />
    <my-custom-form after-submit="home/{{insertedId}}/something" />
    <my-custom-form after-submit="{{insertedId}}/anything" />
</div>

Or maybe there is a better way to do this? I don't know that's why I'm asking. Thanks.

Scot
  • 165
  • 2
  • 14

1 Answers1

0

Try with this

app.directive('myCustomForm', function() {
    return {
        scope: {
          afterSubmit = '@',
        },
        templateUrl: 'myCustomForm.html',
        controller: function($scope) {
            console.log($scope.afterSubmit);
        }
    }
});

Notice that the scope variable name is camelCase (stackOverflow), instead the attribute is dash-case (stack-overflow) This because HTML cannot understand camelCase and javascript cannot understand dash-case

The @ for the variable stand for string. You can use:

  • @ for strings
  • = for variables coming from the controller (ex: after-submit="ctrl.submitUrl")
  • & for callbacks (ex: on-submit="ctrl.submit()")

You should use controller: instead of link: ... Here the reason: AngularJS : link vs compile vs controller

Community
  • 1
  • 1
Matteo Cardellini
  • 876
  • 2
  • 17
  • 41
  • This: `controller: function(scope, element, attr) {}` doesn't appear to be the syntax for the directive's controller! – slackmart May 02 '16 at 01:53
  • What about dynamic injection?, I mean something like: `controller: ['$scope', function($scope) {}]` – slackmart May 02 '16 at 02:00
  • It's not mandatory.. I have a grunt plugin that changes it everytime I build so i don't have to add two things everytime i declare something new. – Matteo Cardellini May 02 '16 at 02:02