Skip to content Skip to sidebar Skip to footer

How To Pass Scope Variable In Ng-init Using Angularjs

I have problem passing the variable declared from the scope to ng-init: so far I have something like this: $scope.x = '10';
https://docs.angularjs.org/api/ng/directive/ngInit).

As for actually doing it....

<div ng-controller="controller" ng-init="x = x">

Solution 2:

Maybe this one can help you:

$scope.x = '10';

<div ng-controller = "controller" ng-init="x">

Solution 3:

If you wanted to push a value in using the ng-init i would use something like this

Js code

angular.module("app",[])
.controller("ctrl",function($scope){
    $scope.x = "this will be replaced"; //not really needed$scope.initialize = function(bar){
        $scope.x=bar;
    }
})

and html

<div ng-app="app" ng-controller="ctrl" ng-init="initialize('your value')">

Solution 4:

If you want to execute a function on a tag where you have a controller, why not simply run the function in the controller's constructor (i.e. function)?

Not everything has to be in the markup.

JS:

angular.module(...).controller('MyController', function ($scope) {
    $scope.myFunction($scope.x);
})

HTML:

<divng-controller="MyController"></div>

Post a Comment for "How To Pass Scope Variable In Ng-init Using Angularjs"