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.
- When I use
datasource, the code executes well. But according to the article, if I usecustomersthen I get the exception cannot read property push of undefined. - When I see the scope in chrome with the custom directive selected, I cannot see the
datasourceand theadd, instead I see thecustomersandaddCustomer. Why isdatasourceandaddnot available in the isolated scope?. If I see the childscope, then i can see thedatasourceand theaddin the isolate bindings. What does this mean? - Can the controller(defined inside the directive) scope access the isolate scope? How?
- How to use
controllerAsin 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.
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.