acid
acid

Reputation: 2149

AngularJS : directive scope

I am trying to set variable in the directive's scope:

HTML:

<div personalize-product>
        Owned: {{ isOwned }}    
</div>

Coffee:

angular.module('yoApp').directive 'personalizeProduct', ->
    restrict: 'A'
    link: (scope, el, attrs) ->
        scope.isOwned = 'maybe'

however it does not work. I'm clearly missing something, but I cannot find an answer in angular docs.

EDIT: I should have mentioned - I don't want to pass isOwned to directive, I want the directive to be responsible for setting it.

Upvotes: 0

Views: 130

Answers (3)

Sten Muchow
Sten Muchow

Reputation: 6711

Here is the working code:

HTML:

  <body ng-app="yoApp">
    <div personalize-product product-id="6">
    </div>

    <div personalize-product product-id="8">
    </div>
  </body>

JS:

angular.module('yoApp', [])
  .directive('personalizeProduct', function() {
    return {
      restrict: 'A',
      scope: {},
      link: function(scope, el, attrs) {
        scope.isOwned = attrs.productId;
      },
      template: '<div>{{isOwned}}</div>'
    }
  })

Upvotes: 2

christang
christang

Reputation: 533

If you are creating a module to hold your directive, you need to specify its dependencies, which are none (note the new Array).

angular.module('yoApp', []).directive 'personalizeProduct', ->
    restrict: 'A'
    link: ($scope) ->
        $scope.isOwned = 'maybe'

Plunker.

See Creation vs Retrieval in Developer Guide / Modules.

Upvotes: 0

Sebastian
Sebastian

Reputation: 17443

There are a couple of flaws in your code.

First you can populate the scope of your directive by using attributes:

<div personalize-product is-owned="isOwned">

Second, in your directive you need to declare the bindings (you can use different types of bindings - take a look at the docs for details):

angular.module('yoApp').directive 'personalizeProduct', ->
  restrict: 'A'
  scope: { isOwned: '=' }
  controller: (scope) ->
    scope.isOwned = 'maybe'

Update (based on the comments added)

If you just want to have an isolated scope for your directive (but not passing anything from the parent scope) declare an empty object for scope:

scope: { }

Upvotes: 0

Related Questions