angularjsangularjs-directiveui-sref

Angularjs custom directive cannot work for ui-sref


First, this works: <a ui-sref="students({courseId: $ctrl.Course.Id})">{{ student.Name }}</a> Which supports that my router works fine.

I create a custom directive: link: "=link"

<div ng-if="$ctrl.link && $ctrl.link.Name && $ctrl.link.State">
            <a ui-sref="{{$ctrl.link.State}}">{{$ctrl.link.Name}}</a>
</div>

Why this cannot work:

<div link="{ Name: 'View Students', State: 'students({courseId: $ctrl.Course.Id})' }">

Here is the error:

Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: Param values not valid for state ‘students’)

Update: My custom directive

angular.module('Foo').component('Bar', {
        controller: LinkController,
        templateUrl: "link.tpl.html",
        transclude: true,
        bindings: {
            link: "=link",
    });

Solution

  • I solved this problem as below:

    How I debug: I try to replace ‘$ctrl.Course.Id’ with 123 (Number), it works. So I know my custom link directive is working.

    <div link="{ Name: 'View Students', State: 'students({courseId: $ctrl.Course.Id})' }">
    

    Then I realized that it is because I put this ‘$ctrl.Course.Id’ inside the single quote, it will parse it as a string, instead of a number.

    So, this is what I did:

    Go to component, make an object:
    this.studentsLink = { Name: 'View Students', State: 'students({courseId:'.concat(this.$stateParams.courseId, '})')};

    My this.$stateParams.courseId is a string. If it is a number, we should do this.$stateParams.courseId.toString()

    Then go to Template:

    <div link="$ctrl.studentsLink">
    

    Hope this help future developers who have the same problem.