0

I'm following Dan Wahlin isolate scope with function parameters. I have a couple of ambiguity in this article. Since there is no response at that site, I opted for stack overflow. I'm new to the javascript/angular world, response in detail is greatly welcomed.

  1. When I use datasource, the code executes well. But according to the article, if I use customers then I get the exception cannot read property push of undefined.
  2. When I see the scope in chrome with the custom directive selected, I cannot see the datasource and the add, instead I see the customers and addCustomer. Why is datasource and add not available in the isolated scope?. If I see the childscope, then i can see the datasource and the add in the isolate bindings. What does this mean?
  3. Can the controller(defined inside the directive) scope access the isolate scope? How?
  4. How to use controllerAs in the directive controller.

Here is the source code.

var app=angular.module('customermodule', []);
app.controller('CustomersController', ['$scope', function ($scope) {
var counter = 0;
$scope.customer = {
    name: 'David',
    street: '1234 Anywhere St.'
};
$scope.customers = [];
$scope.addCustomer = function (name) {
    counter++;
    $scope.customers.push({
        name: (name) ? name : 'New Customer' + counter,
        street: counter + ' Cedar Point St.'
    });
};
$scope.changeData = function () {
    counter++;
    $scope.customer = {
        name: 'James',
        street: counter + ' Cedar Point St.'
    };
};
}]);
app.directive('isolatedScopeWithController', function () {
return {
    restrict: 'EA',
    scope: {
        datasource: '=',
        add: '&',
    },
    controller: function ($scope) {
        $scope.addCustomer = function () {
        //Call external scope's function
        var name = 'New Customer Added by Directive';
        $scope.add({ name: name });

        //I get exception here if i use customers here. Instead If I use datasource, it works well.
        $scope.customers.push({
            name: name
        });
    };
},
    template: '<button ng-click="addCustomer()">Add Customer</button> 
<ul>' +
        '<li ng-repeat="cust in customers">{{ cust.name }}</li></ul>'
  };
 });

I want to know if I'm missing out anything in this case or the article is unintendedly mistake.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Raida Adn
  • 405
  • 1
  • 6
  • 17
  • 1
    Add a `console.log($scope)` in the controller of isolate scope directive. It will log the isolate scope. The $scope injected to that controller *is* the isolate scope of that directive. – georgeawg Aug 02 '18 at 13:25
  • 1
    Avoid asking multiple distinct questions at once. It makes it hard to write a specific answer. – georgeawg Aug 02 '18 at 13:30

0 Answers0