Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-init pass element to scope

Tags:

angularjs

Is there a way to get the current element where my ng-init is currently binded on?

For example:

<div ng-init="doSomething($element)"></div>

I believe that there is a way for ng-click but I can't do this using ng-init like this:

<div ng-click="doSomething($event)"></div>

Controller:

$scope.doSomething = function(e){ 
    var element = angular.element(e.srcElement); 
}

How do I do this with ng-init?

like image 304
Harold Anthony Ocampo Avatar asked Mar 10 '14 05:03

Harold Anthony Ocampo


People also ask

What is $scope and rootScope?

Root Scope All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.

What is use of $scope in angular?

$scope is a child object that is used to bind the HTML(view) & Javascript(Controller) in a webpage. It is created with the ng-app directive. It is created with the ng-controller directive. It is available globally for all the controllers, i.e, the property assigned with “$rootscope” can be used anywhere.

What is $scope and $rootScope in Angularjs?

"$rootScope” is a parent object of all “$scope” angular objects created in a web page. $scope is created with ng-controller while $rootscope is created with ng-app . Follow this answer to receive notifications.


2 Answers

Your HTML:

<div ng-app='app' ng-controller="Ctrl">
    <div my-dir></div>
</div>

Your Javascript:

var app = angular.module('app', [], function () {});

app.controller('Ctrl', function ($scope) {
    $scope.doSomething = function (e) {
        alert(e);
    };
});

app.directive('myDir', function () {
    return function (scope, element, attrs) {
        scope.doSomething(element);
    };
});

From above, element will be your DOM object.

like image 174
Sam YC Avatar answered Oct 13 '22 03:10

Sam YC


Don't do it.

As @CodeHater said, handling DOM manipulation in a directive is a better solution than engaging controller with the element.

like image 1
Pablo Avatar answered Oct 13 '22 01:10

Pablo