Stefan Walther
Stefan Walther

Reputation: 938

Passing scope to AngularJS directive

I have a specific scenario for a AngularJS directive:

I cannot change in this scenario the main-scope because this is owned by another application (more or less a plugin-mechanism).

Thanks & Regards Stefan

Upvotes: 1

Views: 90

Answers (1)

Stefan Walther
Stefan Walther

Reputation: 938

If think I have found the solution:

Sample Html:

<wi-view data-layout="{{passLayout}}"></wi-view>
<hr />
Original property: {{layout.property1}}

Sample Controller:

app.controller('wiController', function($scope) {

    // Simulating the original scope values
    $scope.layout = {};
    $scope.layout.property1 = 'Original Value';

    // New scope values, just here for binding it to the controller
    var passLayout = {};
    passLayout.property1 = 'Value Overwritten';
    passLayout.property2 = 'Another Property';
    $scope.passLayout = passLayout;

});

Sample Directive:

app.directive('wiView', function () {
var linkFunction = function(scope, elems, attrs) {

    if (attrs.layout !== undefined) {
        scope.layout = angular.fromJson(attrs.layout);
    }
};

return {
    restrict: "E",
    scope: true,
    priority: 0,
    link: linkFunction,
    template: '<div>Hello, {{layout.property1}}!</div>'
};

});

Upvotes: 1

Related Questions