user1888955
user1888955

Reputation: 626

How to retrieve custom property in isolate scope?

I've read quite a lot examples on how to do binding in an isolate scope but not how to retrieve scope custom properties in template.

I think the fix must be very simple but I just don't figure out what's wrong here

<!doctype html>
<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script>
</head>
<body>
  <div my-directive>

  </div>

  <script>
    angular.module('myApp', [])
    .directive('myDirective', function() {
      return {
        restrict: 'A',
        scope: {
            data.myProperty:"1234"
        },
        template:'Inside myDirective, isolate scope: {{ data.myProperty }}'
      };
    })
  </script>

</body>
</html>

Somehow, data.myProperty couldn't be reached.

Upvotes: 0

Views: 103

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You can't directly use and access bounded properties in bindings like you were doing data.myProperty:"1234". It will eventually result in error.

You have to pass custom property via attribute of your directive. Over here you can consider adding custom-data attribute, add mention the scope property name over it. So it would be passed to isolated scope directive.

Controller

$scope.data = {
   myProperty: 'My Property Value'
}

Html

<div my-directive custom-data="data">

</div>

directive

angular.module('myApp', [])
.directive('myDirective', function() {
  return {
    restrict: 'A',
    scope: {
        customData: '=data'
        //without alias it will look like below.
        //customData: '='
    },
    template:'Inside myDirective, isolate scope: {{ data.myProperty }}'
    //without alias template would look like below
    //template:'Inside myDirective, isolate scope: {{ customData.myProperty }}'
  };
})

Note: It seems like you are using older unstable version. If possible update angular to latest angularjs 1.7.x version, to find more features and performant angularjs. After 1.5.x version, you could also use < inside binding (customData: '<data') to keep one way data binding flow. Just to not confuse you I used =(two way data binding) for demo.

Upvotes: 1

Related Questions