3

I have problem passing the variable declared from the scope to ng-init:

so far I have something like this:

$scope.x = '10';

<div ng-controller = "controller" ng-init="function(x)">

How do I pass x var from the scope inside ng-init function?

4 Answers 4

6

A lot of people will tell you you shouldn't do this (as mentioned in the docs here: https://docs.angularjs.org/api/ng/directive/ngInit).

As for actually doing it....

<div ng-controller="controller" ng-init="x = x">
Sign up to request clarification or add additional context in comments.

Comments

2

Maybe this one can help you:

$scope.x = '10';

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

Comments

1

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')">

Comments

0

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:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.